使用Lodash在嵌套数组以及其他操作中查找属性

时间:2018-08-14 07:02:43

标签: javascript lodash

使用Lodash和以下示例对象数据数组(其中也包含嵌套数组),我该怎么做:

1)在Child-A中找到名称“ children array”?

2)在Child-A管理员中找到名称“ children array, determine if it has the property”:“ Y”`?

3)根据项目2,从子数组(嵌套)中删除实际属性admin: "Y"

data = [
  {
   name: "A",
   type: "AA",
   children: [ { id: 1, name: "Child-A", admin: ["Y"] }],
   other: "NA"
  },
  {
   name: "B",
   type: "BB",
   children: [ { id: 2, name: "Child-B" }],
   other: "NA"
  },
  {
   name: "C",
   type: "CC",
   children: [ { id: 3, name: "Child-C" }],
   other: "NA"
  }
]

我是Lodash的新手,曾经尝试过_.find()_.get()

尝试过:

const theChild = _.find(data.children, {'name': childName});

从这里,我回到undefined

2 个答案:

答案 0 :(得分:1)

我从没用过Lodash,有人说这很棒,但是到目前为止,我已经设法使用纯JS进行了这种对象操作,所以去了:

(我一口气做了所有事情,找到对象,检查它是否具有admin属性,将其删除。)

let data = [{
    name: "A",
    type: "AA",
    children: [{
      id: 1,
      name: "Child-A",
      admin: ["Y"]
    }],
    other: "NA"
  },
  {
    name: "B",
    type: "BB",
    children: [{
      id: 2,
      name: "Child-B"
    }],
    other: "NA"
  },
  {
    name: "C",
    type: "CC",
    children: [{
      id: 3,
      name: "Child-C"
    }],
    other: "NA"
  }
]

data = data.map(obj => {
  obj.children = obj.children.map( child => {
      if(child.name !== "Child-A") return child;
      let hasY = child.admin && child.admin.includes("Y");
      console.log("Has admin==='Y' : ", hasY);
      delete child.admin;
      return child;
  })
  return obj;
})

console.log("Transformed data = ", data)

答案 1 :(得分:1)

love lodash,learn lodash ...

_.forEach(data, (d, i) => {
  let fIdx= _.findIndex(d.children, {'name': 'Child-A', 'admin': ['Y']});
  if(fIdx > -1) delete data[i].children[fIdx].admin;
});

注意:这将找到您条件的所有实例