以下是我的对象数据
var testObj ={
"AAA": {
"number":{
"123":{},
"5435":{},
"5466":{}
}
},
"BBB":{
"number":{
"54656":{},
"111":{},
"4656":{}
}
},
"CCC":{
"number":{
"214543":{},
"32432":{},
"12435":{}
}
},
"DDD":{
"number":{
"343":{},
"123213":{},
"111":{}
}
}
}
如何过滤此对象并获取一个编号为“111”的新对象?
var testObj ={
"BBB":{
"number":{
"54656":{},
"111":{},
"4656":{}
}
},
"DDD":{
"number":{
"343":{},
"123213":{},
"111":{}
}
}
}
答案 0 :(得分:0)
您可以使用Object.keys()
和reduce()
并使用hasOwnProperty()
检查密钥
var testObj = {"AAA":{"number":{"123":{},"5435":{},"5466":{}}},"BBB":{"number":{"111":{},"4656":{},"54656":{}}},"CCC":{"number":{"12435":{},"32432":{},"214543":{}}},"DDD":{"number":{"111":{},"343":{},"123213":{}}}}
var result = Object.keys(testObj).reduce(function(r, key) {
if (testObj[key].number.hasOwnProperty('111')) {
r[key] = testObj[key]
}
return r;
}, {})
console.log(result)

答案 1 :(得分:0)
您可以使用Object.keys
和Array.prototype.reduce
获取所有对象键,使用自定义谓词过滤掉(在这种情况下,是否设置了foo.number.111
)并构建对象结果:
const testObj = {
"AAA": {
"number": {
"123": {},
"5435": {},
"5466": {}
}
},
"BBB": {
"number": {
"54656": {},
"111": {},
"4656": {}
}
},
"CCC": {
"number": {
"214543": {},
"32432": {},
"12435": {}
}
},
"DDD": {
"number": {
"343": {},
"123213": {},
"111": {}
}
}
};
const result = Object.keys(testObj).filter(key => {
return testObj[key].number['111'];
}).reduce((p, key) => {
p[key] = testObj[key];
return p;
}, {});
console.log(result);

答案 2 :(得分:0)
您可以将Object.keys()
,for..of
循环,JSON.stringify()
,RegExp.prorotype.test()
与RegExp
<property name including quotes followed by ":">
,delete
一起使用。要保留原始对象,请使用Object.assign()
创建具有原始对象属性的新对象,从新对象中迭代和delete
个对象。
var testObj ={
"AAA": {
"number":{
"123":{},
"5435":{},
"5466":{}
}
},
"BBB":{
"number":{
"54656":{},
"111":{},
"4656":{}
}
},
"CCC":{
"number":{
"214543":{},
"32432":{},
"12435":{}
}
},
"DDD":{
"number":{
"343":{},
"123213":{},
"111":{}
}
}
}
let prop = `"111"`, re = new RegExp(prop + ":");
for (let o of Object.keys(testObj))
if (!re.test(JSON.stringify(testObj[o])))
delete testObj[o];
console.log(testObj);
答案 3 :(得分:0)
您可以执行以下操作;
var testObj ={
"AAA": {
"number":{
"123":{},
"5435":{},
"5466":{}
}
},
"BBB":{
"number":{
"54656":{},
"111":{},
"4656":{}
}
},
"CCC":{
"number":{
"214543":{},
"32432":{},
"12435":{}
}
},
"DDD":{
"number":{
"343":{},
"123213":{},
"111":{}
}
}
},
filtered = Object.keys(testObj).filter(k => Object.keys(testObj[k].number).includes("111"))
.reduce((p,k) => (p[k] = Object.assign({},testObj[k]),p),{});
console.log(filtered);