我有两个对象:
OBJ1
{
"uuid": "",
"open_bal_qty": 0,
"open_bal_value": 0,
"qty_min": 0,
"qty_med": 0,
"qty_max": 0,
"kedai_uuid": "198ceaef-4ced-4207-9ba0-62afbb42bb85"
}
OBJ2
{
"uuid": "",
"open_bal_qty": 0,
"open_bal_value": 0,
"kedai_uuid": "198ceaef-4ced-4207-9ba0-62afbb42bb85"
}
如何删除obj2
中不存在的复制和获取元素,以便我的新obj将是:
newObj
{
"qty_min": 0,
"qty_med": 0,
"qty_max": 0,
}
我可以使用lodash pick
,但我不想手动输入我要过滤的密钥名称。
const newObj = pick(obj1, [
'qty_min',
'qty_med',
'qty_max',
]);
提前致谢。
答案 0 :(得分:2)
使用lodash,您可obj1
obj2
const obj1 = {"uuid":"","open_bal_qty":0,"open_bal_value":0,"qty_min":0,"qty_med":0,"qty_max":0,"kedai_uuid":"198ceaef-4ced-4207-9ba0-62afbb42bb85"};
const obj2 = {"uuid":"","open_bal_qty":0,"open_bal_value":0,"kedai_uuid":"198ceaef-4ced-4207-9ba0-62afbb42bb85"};
const newObj = _.omit(obj1, _.keys(obj2));
console.log(newObj);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
{/ 3}}:
{{1}}
{{1}}
答案 1 :(得分:1)
您可以将_.pick
与_.difference
结合使用,找出两个对象之间的区别&#39;钥匙和挑选这些钥匙:
const obj1 = {
"uuid": "",
"open_bal_qty": 0,
"open_bal_value": 0,
"qty_min": 0,
"qty_med": 0,
"qty_max": 0,
"kedai_uuid": "198ceaef-4ced-4207-9ba0-62afbb42bb85"
};
const obj2 = {
"uuid": "",
"open_bal_qty": 0,
"open_bal_value": 0,
"kedai_uuid": "198ceaef-4ced-4207-9ba0-62afbb42bb85"
};
const obj1Keys = _.keys(obj1); //or Object.keys
const obj2Keys = _.keys(obj2);
console.log(_.pick(obj1Keys > obj2Keys ? obj1 : obj2, _.difference(obj1Keys, obj2Keys)))
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
&#13;
答案 2 :(得分:1)
使用for..in
迭代对象,Object.hasOwnProperty
检查第二个对象是否具有相同的密钥
var obj1 = {
"uuid": "",
"open_bal_qty": 0,
"open_bal_value": 0,
"qty_min": 0,
"qty_med": 0,
"qty_max": 0,
"kedai_uuid": "198ceaef-4ced-4207-9ba0-62afbb42bb85"
}
var obj2 = {
"uuid": "",
"open_bal_qty": 0,
"open_bal_value": 0,
"kedai_uuid": "198ceaef-4ced-4207-9ba0-62afbb42bb85"
}
var newObj = {};
for (var keys in obj1) {
if (!obj2.hasOwnProperty(keys)) {
newObj[keys] = obj1[keys]
}
}
console.log(newObj)