简体   繁体   中英

JavaScript Array push() method use to the id as the index value?

I want to use id as the index value and then generate a new array. What better way do you have?

This is the result I want

Arr:Array[2]
3:"a"
8:"b"

Before processing

Arr:Array[2]
0:"a"
1:"b"

My code

 var data = [{ id: 3, name: 'a' }, { id: 8, name: 'b', } ] var arr = [] const p = data.map(item => { arr[item.id].push(item.name) }) console.log(p) 

You could use reduce , initialised with an empty array, set each index with id , and each value with name :

 var data = [{ id: 3, name: 'a' }, { id: 8, name: 'b', } ] console.log(data.reduce((a, {id, name}) => (a[id] = name, a), [])) 

NOTE, you cannot have an array without indexes between values. Javascript will automatically fill these with undefined

If this doesn't fit your needs, then the only other option is to use an object (or a map but that's more complicated :P) , which can still act like an array in a sense:

 var data = [{ id: 3, name: 'a' }, { id: 8, name: 'b', } ] const obj = data.reduce((a, {id, name}) => (a[id] = name, a), {}) console.log(obj) console.log(obj[3]) // a console.log(obj[8]) // b 

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