简体   繁体   中英

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?

尝试这个:

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

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; }

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM