我有jsonArray如下
JSONArray childern as
[{"id":2,"label":"w","remoId":135},
{"id":3,"childern":null,"loc":146,"label":"Loc-w"},
{"id":4,"childern":null,"loc":147,"label":"Loc-newjk"}
]
我想将id = 3的JSONObject的childern键更改为childernArray,其中
childernArray is [{"id":6,"label":"w"},{"id":7,"label":"w"}]
我想要关注输出
[{"id":2,"label":"w","remoId":135},
{"id":3,
"childern":[{"id":6,"label":"w"},
{"id":7,"label":"w"}],
"loc":146,"label":"Loc-w"},
{"id":4,"childern":null,"loc":147,"label":"Loc-newjk"}]
我该怎么做?
答案 0 :(得分:1)
使用Array.prototype.reduce() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
jsonArray.reduce(function(previousValue, currentValue, index, array) {
if(currentValue.id == 3) {
currentValue.children = childrenArray;
}
previousValue.push(currentValue);
return previousValue;
}, []);