过滤嵌套数组

时间:2019-03-09 02:13:01

标签: javascript ecmascript-6

const array = [{ "title": "Carros", "data" : [{ "nome": "Mustang" }, {"nome": "Camaro"}]}];
   
let filteredArray = array
  .filter((element) => 
element.data.some((subElement) => subElement.nome == "Mustang"))
  .map(element => {
return Object.assign({}, element, {nome : element.data.filter(subElement => subElement.nome == "Mustang")});
  }); 

filteredArray总是返回相同的数组,但带有子"nome"元素。

我想要的是搜索“ mus”或“ tang”或“ mustang”或“ mu”并返回:

[{ "title": "Carros", "data" : [{ "nome": "Mustang" }]}];

如果我还有另一列,则相同:

[{ "title": "Carros", "data" : [{ "nome": "Mustang" }]},
{ "title": "Motos", "data" : [{ "nome": "Yamaha }]}];

并且搜索“ mustang”需要返回:

const array = [{ "title": "Carros", "data" : [{ "nome": "Mustang" }]},
{ "title": "Motos", "data" : [] }];

我需要保持相同的结构,但只更改嵌套的“数据”。

3 个答案:

答案 0 :(得分:0)

  let array = [{ title: "Carros", data: [{ nome: "Mustang" }, {nome: "Camaro"}]}];
function Query(data) {


    let newData = [...array[0].data].filter((x,i) => x.nome === data)
    array = [{...array[0],data: newData }]
    console.log(array);
}
Query("Mustang")

我对打字稿不熟悉,但这是一些普通的js

答案 1 :(得分:0)

const array = [{ "title": "Carros", "data" : [{ "nome": "Mustang" }]},
{ "title": "Motos", "data" : [{ "nome": "Yamaha" }]}];

function filterStuff(array, deepname) {
    return array.map(element => ({
        ...element,
        data: element.data.filter(deepElement => deepElement.nome === deepname)
    }))
}

console.log(JSON.stringify(filterStuff(array, "Mustang")));

// Output:
// [{"title":"Carros","data":[{"nome":"Mustang"}]},{"title":"Motos","data":[]}]

这为您提供了一种方法来调用该深层元素进行过滤,并且更加干净。

答案 2 :(得分:0)

如果可以使用Lodash + Deepdash,则可以执行以下操作:

// filter by Mustang(no empty categories)
let res = _.filterDeep(data,(v)=>_.includes(v.nome,"Mus"),{tree:{children:"data"}});

// get all empty categories
let structure = _.omitDeep(data,/\.data.+/);

_.merge(structure,res);
console.log(structure);

这里是Codepen for this