我有一个对象数组,我正在尝试在对象中找到值并删除已在存在对象中找到的值。例如,
当前JSON对象:
exist=[{"x":6811,"y":15551,"a":["aa","ab","ac"]},{"x":6811,"y":15552,"a":["bb"]},{"x":6812,"y":15551,"a":["aa","cc"]}]
我想找到值为aa的“a”键
最后的结果是
exist= [{"x":6811,"y":15552,"a":["bb"]}]
found= [{"x":6811,"y":15551,"a":["aa","ab","ac"]},{"x":6812,"y":15551,"a":["aa","cc"]}]
答案 0 :(得分:0)
你可以不用下划线做到这一点:
let exist= [
{ x: 6811, y: 15551, a: ['aa', 'ab', 'ac'] },
{ x: 6811, y: 15552, a: ['aa', 'bb'] },
{ x: 6812, y: 15551, a: ['cc'] },
];
const found = exist.filter(({ a }) => a.includes('aa'));
exist = exist.filter(({ a }) => !a.includes('aa'));
console.log('found:', found);
console.log('exist:', exist);
答案 1 :(得分:0)
您可以将.reject 与 .contains和_.result组合使用
exist=[
{"x":6811,"y":15551,"a":["aa","ab","ac"]},{"x":6811,"y":15552,"a":["bb"]},{"x":6812,"y":15551,"a":["aa","cc"]}, {"x":6812,"y":15551}
]
exist = _.reject(exist, function(item){
return _.contains(_.result(item, "a"), "aa");
})
console.log(exist);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>