简体   繁体   English

在数组中创建并推送键值 object

[英]create and push key value object in array

I have an array:我有一个数组:

const data = [{"label": "a", "value": 4}, {"label": "b", "value": 1}, {"label": "c", "value": 2}]

I want to create a new array of objects where I have to give key and value in it.我想创建一个新的对象数组,我必须在其中提供键和值。

For eg,:例如:

const newArr = [{1,4},{2,1},{3,2}]

here first item of an object is the key, which has to increase as the number of objects increase, and second item is the value from data .这里 object 的第一项是键,它必须随着对象数量的增加而增加,第二项是来自datavalue

 const data = [{"label": "a", "value": 4}, {"label": "b", "value": 1}, {"label": "c", "value": 2}]; const out = data.map((item, index) => [index + 1, item.value]); console.log(out);

I hope this is your solution:我希望这是您的解决方案:

 const data = [ { label: 'a', value: '4' }, { label: 'b', value: '1' }, { label: 'c', value: '2' }, ] const newArrOfObj = data.reduce((arr, current, index)=> [...arr, {[index+1]:current.value}], []); console.log(newArrOfObj) //[ { 1: '4' }, { 2: '1' }, { 3: '2' } ]

To push an object into an array, call the push() method, passing it the object as a parameter.要将 object 推入数组,请调用push()方法,将 object 作为参数传递给它。 For example, arr.push({name: 'Tom'}) pushes the object into the array.例如, arr.push({name: 'Tom'})将 object 压入数组。 The push method adds one or more elements to the end of the array. push方法将一个或多个元素添加到数组的末尾。

index.js索引.js

 let arr = []; const obj = {name: 'Tom'}; arr.push(obj); console.log(arr); // ️ [{name: 'Tom'}]

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

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