我有一个JSON对象:
[{"box":1,"parent":[],"child":[{"boxId":2},{"boxId":3}]},{"box":2,"parent":[{"boxId":1}],"child":[]}]
我想删除带有boxId = 2的"child":[{"boxId":2}
。我正在使用,映射函数如下:
Arr.map(function (box) {
box.child.map(function (p) {
p.remove();
});
});
它不起作用。我收到错误。
。删除不是函数`
有什么方法可以删除特定元素吗?
修改
例如:我想从子项中删除{"boxId":2}
,生成的JSON应该是:
[{"box":1,"parent":[],"child":[{"boxId":3}]},{"box":2,"parent":[{"boxId":1}],"child":[]}]
答案 0 :(得分:1)
将Array.prototype.map()与Array.prototype.forEach()
一起使用
var arr = [{"box":1,"parent":[],"child":[{"boxId":2},{"boxId":3}]},{"box":2,"parent":[{"boxId":1}],"child":[]}];
// Loop over main array
arr.map(function(e) {
// Get the child element array and iterate over it
return e.child.forEach(function(c, i) {
// If box to remove found
if (c.boxId === 2) {
// Remove the element from main array element
delete e.child.splice(i, 1);
}
});
});
console.log(arr);
document.getElementById('output').innerHTML = JSON.stringify(arr, 0, 4);
<pre id="output"></pre>
答案 1 :(得分:1)
试试这个
import json
my_list = [['apple',{'john':3,'anna':4,'kitty':6}],['pear',{'john':4,'anna':3,'kitty':3}]]
name_list = [item[1] for item in my_list] # [{'john': 3, 'kitty': 6, 'anna': 4}, {'john': 4, 'kitty
names = name_list[0].keys() # ['john', 'kitty', 'anna']
name_values = [[item[key] for item in name_list] for key in names] # [[3, 4], [6, 3], [4, 3]]
result = {
'key': [item[0] for item in my_list],
'value': [
{'name': name, 'value': value}
for (name, value) in zip(names, name_values)
]
}
print(json.dumps(result, indent=4))