javascript 使用基于嵌套值的数组筛选对象数组

2mbi3lxu  于 2023-01-19  发布在  Java
关注(0)|答案(8)|浏览(186)

我尝试过滤一个数组,基于一些嵌套对象。我准备了一些Fiddle
输入数组如下所示:

let arrayOfElements = 
    [
        {
           "name": "a",
           "subElements": 
           [
             {"surname": 1},
             {"surname": 2}
           ]
        },
        {
           "name": "b",
           "subElements": 
           [
             {"surname": 3},
             {"surname": 1}
           ]
        },
        {
           "name": "c",
           "subElements": 
           [
             {"surname": 2},
             {"surname": 5}
           ]
        }
    ];

我希望这种情况下的输出如下所示:

let filteredArray = 
    [
        {
          "name": "a",
          "subElements": 
          [
            {"surname": 1}
          ]
        },
        {
          "name": "b",
          "subElements": 
          [
            {"surname": 1}
          ]
        }
];

我用这个公式来做这件事:

let filteredArray = arrayOfElements.filter((element) => element.subElements.some((subElement) => subElement.surname === 1));

输出几乎是好的,但它返回的对象与所有的对象与姓氏(更好地检查小提琴:D),而不是削减他们了。

a0zr77ik

a0zr77ik1#

这样,您可以在数组中进行任意深度的筛选,并在任何级别筛选元素,

arrayOfElements.map((element) => {
  return {...element, subElements: element.subElements.filter((subElement) => subElement.surname === 1)}
})

Spread运算符将扩展element,然后过滤的subElements将覆盖元素中的subElements

jhiyze9q

jhiyze9q2#

调用filter之后,需要将结果通过管道传输到map,如下所示:

let filteredArray = arrayOfElements
  .filter((element) => 
    element.subElements.some((subElement) => subElement.surname === 1))
  .map(element => {
    let newElt = Object.assign({}, element); // copies element
    return newElt.subElements.filter(subElement => subElement.surname === '1');
  });

这里我假设你不想操作原始数组,所以我使用Object.assign。

hkmswyz6

hkmswyz63#

let filteredArray = arrayOfElements
  .filter((element) => 
    element.subElements.some((subElement) => subElement.surname == 1))
  .map(element => {
    return Object.assign({}, element, {subElements : element.subElements.filter(subElement => subElement.surname == 1)});

  });
tpxzln5u

tpxzln5u4#

只是改进了上面的答案

let elements = 
    [
        {
           "name": "a",
           "subElements": 
           [
             {"surname": 1},
             {"surname": 2}
           ]
        },
        {
           "name": "b",
           "subElements": 
           [
             {"surname": 3},
             {"surname": 1}
           ]
        },
        {
           "name": "c",
           "subElements": 
           [
             {"surname": 2},
             {"surname": 5}
           ]
        }
    ];
var value = 1;

var filteredArray = elements
.filter(element => element.subElements
  .some(subElement => subElement.surname === value)
)
.map(element => {
  let n = Object.assign({}, element, {'subElements': element.subElements.filter(
    subElement => subElement.surname === value
  )})
  return n;
})

console.log(filteredArray)
kkih6yb8

kkih6yb85#

尝试此解决方案:

data_filter = arrayOfElements.filter(function (element) {
    return element.subElements.some( function (subElement) {
        return subElement.surname === surname
    });
});
aamkag61

aamkag616#

您也可以使其通用:
逻辑

  • 找出所有不同的姓氏并循环遍历
  • 过滤每个对象以检查姓氏是否存在。如果存在,使用Object.assign复制对象并将subElements值设置为过滤列表。
  • 创建一个临时数组来保存所有相似的对象,并将复制的对象推到其中。
  • 在每次迭代不同姓氏时将此数组推到最终数组。

样品

let arrayOfElements=[{name:"a",subElements:[{surname:1},{surname:2}]},{name:"b",subElements:[{surname:3},{surname:1}]},{name:"c",subElements:[{surname:2},{surname:5}]}];
 let distinct_surnames = [];
 arrayOfElements.forEach(function(el) {
   el.subElements.forEach(function(s) {
     if (distinct_surnames.indexOf(s.surname) < 0) distinct_surnames.push(s.surname)
   });
 })

 let result = [];
 distinct_surnames.forEach(function(sn) {
   let inter = [];
   arrayOfElements.forEach(function(el) {
     let f = el.subElements.filter(function(sub) {
       return sub.surname === sn;
     });
     if (f.length > 0) {
       let _tmp = Object.assign({}, el);
       _tmp.subElements = f;
       inter.push(_tmp);
     }
   });
   result.push(inter);
 })
 console.log(result)

**注:**箭头函数用于保持this的引用。如果您不在函数内部使用this,也可以使用普通函数。

8qgya5xd

8qgya5xd7#

function display_message() {
  let arrayOfElements = [{
    "name": "a",
    "subElements": [{
      "surname": 1
    }, {
      "surname": 2
    }]
  }, {
    "name": "b",
    "subElements": [{
      "surname": 3
    }, {
      "surname": 1
    }]
  }, {
    "name": "c",
    "subElements": [{
      "surname": 2
    }, {
      "surname": 5
    }]
  }];
  // console.log(arrayOfElements);
var surname = 1;
  let filteredArray = arrayOfElements.filter((element) => element.subElements.some((subElement) => subElement.surname === surname));

  for(var data in filteredArray){
    filteredArray[data].subElements = {"surname": surname};
    }
  console.log(filteredArray);

}
<input type="button" onclick="display_message();" value="click"/>
mcdcgff0

mcdcgff08#

let filteredArray = arrayOfElements
    .filter((element) => 
        element.subElements.some((subElement) => subElement.surname === 1))
    .map(element => {
        let newElt = Object.assign({}, element); // copies element
        newElt.subElements = newElt.subElements.filter(subElement => subElement.surName === '1'); 
        return newElt;
    });

更准确地说

相关问题