简体   繁体   English

向JSON数组JavaScript中的每个值添加一个键

[英]Add a key to each value in json array javascript

I would like to transform the below JSon. 我想转换下面的JSon。 The input JSon array can be of any size. 输入JSon数组可以是任何大小。 I know its a basic question but I can't find the duplicate. 我知道这是一个基本问题,但找不到重复的问题。

 var input = [{
    "value": 1
 }, {
    "value": 2
 }]

 var output = [{
    "key": {
        "value": 1
    }
 }, {
    "key": {
        "value": 2
    }
 }]

Appreciate all the help. 感谢所有帮助。

Create a new array and use Array#forEach to push an object with key = key and a currently iterated object from input as the value. 创建一个新数组,并使用Array#forEach推送一个key = key的对象,并将input当前迭代的对象作为值。

 var input = [{value:1},{value:2}], result = []; input.forEach(v => result.push({ 'key': v })); console.log(result); 

Try using this, this should solve your problem 尝试使用它,这应该可以解决您的问题

output = input.map(value => ({ "key": value }) );
console.log(output);

I used ES6 for simplicity, but this does exactly the same. 为了简单起见,我使用了ES6,但这完全相同。

I think this will be the most oldschool and hands-on way of doing this. 我认为这将是最古老,最实际的做法。

 var input = [{ "value": 1 }, { "value": 2 }], output = [], newItem, i = 0, ii = input.length; for(i; i<ii; i++){ newItem = {}; newItem.key = {"value":input[i].value}; output.push(newItem); } console.log(output) 

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

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