hgkim
hgkim

Reputation: 95

how to add key of object in array?

Guys. I have array like this

array = [{name:"A",data:"..."},{name:"B",data:"..."},{name:"C",data:"..."}]

And I want to edit this array to

array = [ "A":{name:"A",data:"..."},"B":{name:"B",data:"..."},"C":{name:"C",data:"..."}

How could I set object key from its own value?

Upvotes: 2

Views: 93

Answers (4)

Darshana Pathum
Darshana Pathum

Reputation: 669

Just do this.

var arr = [{name:"A",data:"..."},{name:"B",data:"..."},{name:"C",data:"..."}]

var output = arr.map(elem => ({[elem.name]: elem}))

console.log(output)

Upvotes: 0

Vectrobyte
Vectrobyte

Reputation: 1475

JavaScript array doesn't work that way. An array's index value can only have an increasing numeric indexes([0, 1, ..., n]). If you wan't to create such list you can create the object instead of an array.

const array = [{name:"A",data:"..."},{name:"B",data:"..."},{name:"C",data:"..."}];
const newList = {};

array.forEach(obj => {
    newList[obj.name] = obj;
});

console.log({ newList });

In this way you can create the object out of array. You can then loop the object's keys like in arrray using:

Object.keys(newList).forEach((key) => {
  console.log(newList[key]);
})

. Hope it helps.

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386550

For getting an object, you could take Object.fromEntries with the mapped key/value pairs

var array = [{ name: "A", data: "..." }, { name: "B", data: "..." }, { name: "C", data: "..." }],
    result = Object.fromEntries(array.map(o => [o.name, o ]));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 2

Max
Max

Reputation: 1048

Try this:

console.log(array.map(el => ({[el.name]: el})));

Upvotes: 2

Related Questions