首页 > 解决方案 > 如果 Javascript 中不存在默认数组过滤器对象,如何获取它

问题描述

我有一个数组:

const data = [
              {location: "Phnom Penh", sale: 1000 },
              {location: "Kandal", sale: 500 },
              {location: "Takeo", sale: 300 },
              {location: "Kompot", sale: 700 },
              {location: "Prey Veng", sale: 100 },
              {location: "Seam Reap", sale: 800 },
              {location: "Null", sale: 0}
            ];

这是我的功能过滤器:

function getSale(data, arr) {
  return data
    .filter(el => arr.includes(el.location))
}
arr = getSale(data, ['Phnom Penh', 'AA', 'Kompot', 'BB']);
console.log(arr);
result: [{
    location: "Phnom Penh",
    sale: 1000
  },
  {
    location: "Kompot",
    sale: 700
  }
]

如果在过滤器中找不到“AA”,我希望它得到“空”对象。

我的目的我想要这样的结果:

 result: [
  {location: "Phnom Penh", sale: 1000},
  {location: "Null", sale: 0},
  {location: "Kompot", sale: 700},
  {location: "Null", sale: 0}
 ]

我怎样做?感谢帮助。

标签: javascriptarrays

解决方案


您应该使用.map.find

const data = [
  { location: 'Phnom Penh', sale: 1000 },
  { location: 'Kandal', sale: 500 },
  { location: 'Takeo', sale: 300 },
  { location: 'Kompot', sale: 700 },
  { location: 'Prey Veng', sale: 100 },
  { location: 'Seam Reap', sale: 800 },
  { location: 'Null', sale: 0 },
];

function getSale(data, arr) {
  return arr.map(el => {
    const found = data.find(obj => obj.location === el);
    return found ? found : { location: 'Null', sale: 0 };
  });
}
arr = getSale(data, ['Phnom Penh', 'AA', 'Kompot', 'BB']);
console.log(arr);

或者从数据数组创建哈希并直接使用 .map :

const data = [
  { location: 'Phnom Penh', sale: 1000 },
  { location: 'Kandal', sale: 500 },
  { location: 'Takeo', sale: 300 },
  { location: 'Kompot', sale: 700 },
  { location: 'Prey Veng', sale: 100 },
  { location: 'Seam Reap', sale: 800 },
];

const hash = data.reduce((hash, obj) => {
  hash[obj.location] = obj;
  return hash;
}, {});
function getSale(data, arr) {
  return arr.map(el => hash[el] || { location: 'Null', sale: 0 });
}
arr = getSale(data, ['Phnom Penh', 'AA', 'Kompot', 'BB']);
console.log(arr);


推荐阅读