Reputation: 95
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
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
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
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