【问题标题】:JavaScript - Filter a array by iterating on another arrayJavaScript - 通过迭代另一个数组来过滤数组
【发布时间】:2018-02-16 11:16:17
【问题描述】:

第一个对象{array},我要过滤的对象:

const object1 = {
  "count" : 2,
  "result" : [
    { "id": 1 },
    { "id": 2 }
  ]
}

第二个数组:

const array2 = [{
 "id": 1,
 "id": 44
}]

如果object.result[i].id 等于array2[i].id,我想过滤第一个数组object1.result(或创建一个新数组),根据过滤器的数量减少数组计数object1.count元素。

在上面的示例中,我应该有一个新对象:

theNewObject = {
  "count" : 1,
  "result" : [
  { "id": 2 }
 ]
}

【问题讨论】:

  • 你确定你的对象是这样的吗?您不能有重复的属性。
  • 哇...到目前为止,您尝试了什么?
  • 我修改了它@MichałPerłakowski
  • @Exception_al mapfilter 的组合
  • 问题正文中仍有无效的 JSON 对象。

标签: javascript ecmascript-6 iteration


【解决方案1】:

您可以使用Set 并收集所有id 进行过滤。

var object = { count : 2, result : [{ id: 1 }, { id: 2 }] },
    array = [{ id: 1 }, { id: 44 }],
    ids = new Set(array.map(({ id }) => id));
    
object.result = object.result.filter(({ id }) => ids.has(id));
object.count = object.result.length;

console.log(object);

一种倒计时的方法。

var object = { count : 2, result : [{ id: 1 }, { id: 2 }] },
    array = [{ id: 1 }, { id: 44 }],
    ids = new Set(array.map(({ id }) => id));

object.result = object.result.filter(({ id }) => ids.has(id) || !object.count--);

console.log(object);

【讨论】:

  • 否则可以计算出count吗?
【解决方案2】:

您可以将filter() 方法与find() 方法结合使用:

const object1 = {
  count: 2,
  result: [
    { id: 1 },
    { id: 2 },
  ],
};

const array2 = [
  { id: 1 },
  { id: 4 },
];

const filteredResult = object1.result.filter(({ id }) => !array2.find(x => x.id === id));
const object3 = {
  count: filteredResult.length,
  result: filteredResult,
};
console.log(object3);

{ id } 语法是 destructuring assignment

你也可以使用reduce():

const object1 = {
  count: 2,
  result: [
    { id: 1 },
    { id: 2 },
  ],
};

const array2 = [
  { id: 1 },
  { id: 4 },
];

const object3 = object1.result.reduce(
  ({ count, result }, { id }) => array2.find(x => x.id === id)
    ? ({ count, result })
    : ({ count: count + 1, result: result.concat([{ id }]) }),
  { count: 0, result: [] },
);

console.log(object3);

【讨论】:

  • 这就是我需要的,否则无法计算count?以减少为例?
猜你喜欢
  • 2015-11-29
  • 1970-01-01
  • 1970-01-01
  • 2013-09-24
  • 2020-11-25
  • 1970-01-01
  • 1970-01-01
  • 2019-05-05
  • 1970-01-01
相关资源
最近更新 更多