如何从多个嵌套对象中计算特定值的对象数?

时间:2019-04-11 21:24:09

标签: javascript jquery

var foodwebsites = {
  "bacon": [{
    "url": "stackoverflow.com",
  }],
  "icecream": [{
    "url": "example.com",
  }],
  "cheese": [{
    "url": "example.com",
  }]
}

var baconfoodwebsites = foodwebsites.bacon.filter(function(elem) {
  return elem.url == 'example.com';
}).length;

var icecreamfoodwebsites = foodwebsites.icecream.filter(function(elem) {
  return elem.url == 'example.com';
}).length;

var cheesefoodwebsites = foodwebsites.cheese.filter(function(elem) {
  return elem.url == 'example.com';
}).length;

var allfoodwebsites = baconfoodwebsites + icecreamfoodwebsites + cheesefoodwebsites;

console.log(baconfoodwebsites, icecreamfoodwebsites, cheesefoodwebsites, allfoodwebsites)

我想做同样的事情,而不必重复所有这些嵌套的对象(培根,冰淇淋和奶酪)。

我认为答案将是:

var allfoodwebsites = foodwebsites=.filter(function( elem) {
    return elem.url == 'example.com';
}).length;

其他信息:

如果可能的话,我只想使用jQuery + Pure Javascript。

我想用"url": "example.com"

查找所有嵌套对象

4 个答案:

答案 0 :(得分:2)

最好的选择是用于计算进近次数的函数reduce

let foodwebsites = {"bacon": [{"url": "stackoverflow.com",}],"icecream": [{"url": "example.com",}],"cheese": [{"url": "example.com",}]};
let allfoodwebsites = Object.values(foodwebsites).
          reduce((a, array) => a + array.
            reduce((a, {url}) => a + (url === "example.com"), 0), 0);

console.log(allfoodwebsites);

答案 1 :(得分:2)

使用Object.values,Array#reduce()和Array#flat()。请注意,flat()在某些环境中可能需要使用polyfill

let foodwebsites = {"bacon": [{"url": "stackoverflow.com",}],"icecream": [{"url": "example.com",}],"cheese": [{"url": "example.com",}]};


const  getUrlCount = (url) => {
   return Object.values(foodwebsites)
       .flat()
       .reduce((a, {url:u})=> a + (url === u) , 0)

}

console.log(getUrlCount("example.com"))

答案 2 :(得分:1)

解决方案:

您可以创建一个函数,该函数将迭代对象键并在每个访问的键的子对象数组中搜索propertyvalue

let amount = (p, v, i = 0) => 
(Object.keys(foodwebsites).forEach(k => foodwebsites[k].forEach(o => o[p] === v && i++))
, i);

它可以像这样使用:

amount("url", "example.com"); // 2

工作代码段:

var foodwebsites = {
  "bacon": [{
    "url": "stackoverflow.com",
  }],
  "icecream": [{
    "url": "example.com",
  }],
  "cheese": [{
    "url": "example.com",
  }]
}

    let amount = (p, v, i = 0) => 
    (Object.keys(foodwebsites).forEach(k => foodwebsites[k].forEach(o => o[p] === v && i++))
    , i);

console.log(
  amount("url", "example.com")
);
//2

答案 3 :(得分:1)

我实际上已经为所有这些嵌套条目构建了一个数组:

  const sites = Object.values(foodwebsites).flat();

然后,您可以轻松地对其进行迭代并计算所有键:

 const count = (arr, key, value) => arr.reduce((acc, it) => acc + it[key] === value, 0);

 console.log(
   count(sites, "url", "example.com"),
   count(sites, "url", "stackoverflow.com")
 );