0

I want to ask simple question, how to add object name using javascript

I have try this

const data = ["1", "5", "3", "4"]
const obj = this.Tags.reduce((acc,e) => { acc[e] = e; return acc; }, {});

but the output, I need to change number with string name

{
  1: "1",
  3: "3",
  4: "4",
  5: "5"
}

I want the output to be like this, how to do that in javascript ?

{
  value: "1",
  value: "3",
  value: "4",
  value: "5"
}

Thanks

sinzo
  • 119
  • 1
  • 10

3 Answers3

1

I can assume you want this:

let _ = '';
const data = ["1", "5", "3", "4"];
const obj = JSON.stringify(data.sort().reduce((acc, e) => {
    _ += '_';
    acc[`${_}value`] = e;
    return acc;
}, {}), null, 2).replace(/_/g, '');
console.log(obj);
1

The output you want would just be one entry because you can not have dupliceate keys

{
  value: "5"
}

I assume you actually want an array of objects,

const data = ["1", "5", "3", "4"];
const result = data.map(value => ({ value }));
console.log(result);
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

Well, in short, you can't have duplicate keys in an object, so can't have exactly the output you mentioned (here is another thread you can read about it). Here is an example how you can dynamically insert a key/value pair. Just change value${i} to whatever you need your key name to be.

const data = ["1", "5", "3", "4"]
const obj = data.reduce((acc,e,i) => { 
  acc[`value${i}`] = e; 
  return acc; 
}, {});

console.log(obj)

If this is necessary that all of the keys are named value I'd suggest using an array of objects instead (it is also mentioned in the thread I linked).

lacrit
  • 115
  • 5