[英]Using filter() inside the filter() in JavaScript
我在过滤数据时遇到问题,这是我的数据:
var data = {
CustomerInfo: [{ id : 3, name: "c" }],
detail: {company: "Google"},
location: {country: "Italy"},
CustomerInfo2: [{ id : 4, name: "d" }]
};
我想打印每个不是对象格式的名称( data[x][x] !== 'object'
)。 例如,只打印“公司”和“国家”。 这是我的代码:
var dataFiltered = Object.keys(data).filter(function(parent){
return Object.keys(data[parent]).filter(function(child){
return typeof data[parent][child] !== 'object';
});
}).reduce(function(prev, child) {
console.log(prev + " >>> " + data[child]);
});
我有点搞砸了过滤器内的过滤器。
最后我想要这个结果:
company >>> Google
country >>> Italy
你可以做
var data = { CustomerInfo: [{ id : 3, name: "c" }], detail: {company: "Google"}, location: {country: "Italy"}, CustomerInfo2: [{ id : 4, name: "d" }] }; let result = Object.keys(data).reduce((a, b) => { if(typeof data[b] == 'object'){ for(let element of Object.keys(data[b])){ if(typeof data[b][element] != 'object'){ a.push(data[b][element]); console.log(element, '>>>', data[b][element]); } } } return a; },[]); console.log(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.