在JSON中添加数组数据的新元素

时间:2018-05-12 17:43:37

标签: javascript arrays json ajax indexing

我有一个Json动态数据对象。

[{"stock1":"aaaa","stock2":"bbbb"},{"stock1":"aaaa","stock2":"bbbb"},{"stock1":"aaaa","stock2":"bbbb"}]

我必须提供一些数据。

"identifier" : "userid"

然后,我尝试制作这样的代码。

Data.push({"identifier" : "userid"});

,结果是

[{"stock1":"aaaa","stock2":"bbbb"},{"stock1":"aaaa","stock2":"bbbb"},{"stock1":"aaaa","stock2":"bbbb"},{"identifier" : "userid"}]

但我的目标是

[{"stock1":"aaaa","stock2":"bbbb","identifier" : "userid"},{"stock1":"aaaa","stock2":"bbbb","identifier" : "userid"},{"stock1":"aaaa","stock2":"bbbb","identifier" : "userid"}]

如何将一些数据放入现有json数据中的特殊索引?

5 个答案:

答案 0 :(得分:1)

要更新/添加现有数组对象,您可以创建一个简单的 forEach 循环。

Stack snippet

var array = [{"stock1":"aaaa","stock2":"bbbb"},{"stock1":"aaaa","stock2":"bbbb"},{"stock1":"aaaa","stock2":"bbbb"}]

array.forEach(function(item) {
  item["identifier"] = "userid";
})

console.log(array)

答案 1 :(得分:0)

使用export default combineReducers({ contactsList: dataReducer }); 函数为每个元素添加新的键值对



reduce




答案 2 :(得分:0)

我认为map()将完美地为此:



var arr = [{"stock1":"aaaa","stock2":"bbbb"},{"stock1":"aaaa","stock2":"bbbb"},{"stock1":"aaaa","stock2":"bbbb"}]

var result = arr.reduce((r,s) => {
  r.push(Object.assign({}, s, {"identifier" : "userid"}));
  return r;
} , []);
console.log(result);




答案 3 :(得分:0)

你需要推送数组元素而不是数组本身: 所以你需要循环这个JSONArray,然后为每个元素推送新变量,如:

    for(int x-0; x<Data.length; x++){
       Data[x].push({"identifier" : "userid"})
    }

答案 4 :(得分:-1)

试试这个。使用{"Protein":[ ... ],"Hec":[ ... ], "Lec":[ ... ], "F":[ ... ]} 迭代现有数组数据,并使用Object.keys将新数据分配到每个级别:

Object.assign

以下是一些解释var Data = [{"stock1":"aaaa","stock2":"bbbb"},{"stock1":"aaaa","stock2":"bbbb"},{"stock1":"aaaa","stock2":"bbbb"}]; Data = Object.keys(Data).map(function (i) { return Object.assign({}, Data[i], {identifier: 1}); }); console.log(Data); 用法的文档: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign