簡體   English   中英

在 JavaScript 中的 filter() 中使用 filter()

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM