简体   繁体   English

JavaScript Array push()方法使用id作为索引值吗?

[英]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. 我想使用id作为索引值,然后生成一个新数组。 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 : 您可以使用reduce ,使用一个空数组初始化,为每个索引设置id ,并为每个值设置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 JavaScript会自动用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: 如果这不符合您的需求,那么唯一的选择就是使用一个对象(或一个映射,但是更复杂的:P) ,从某种意义上说,它仍然可以像一个数组:

 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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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