根据选择过滤列表

时间:2019-11-03 15:40:28

标签: javascript lodash

鉴于下面的数据,我有两个选择列表,第一个选择列表是显示每个人的名字...第二个选择列表是两个显示所选人的孩子的名字。使用lodash,最简单的方法是什么?

const people = [{
    id: "1",
    name: "bob",
    gender: "male",
    children: [{
      id: "1",
      name: "sarah"
    }]

  },
  {
    id: "2",
    name: "tom",
    gender: "male",
    children: [{
      id: "1",
      name: "lisa"
    }]

  },
  {
    id: "3",
    name: "sue",
    gender: "female",
    children: [{
      id: "1",
      name: "larry"
    }]

  }
]

1 个答案:

答案 0 :(得分:0)

请找到以下解决方案:

import map from "lodash/map";
import partialRight from "lodash/partialRight";
import pick from "lodash/pick";
import find from "lodash/find";

const test = [
  {
    id: "2",
    name: "tom",
    gender: "male",
    children: [
      {
        id: "1",
        name: "lisa"
      }
    ]
  },
  {
    id: "3",
    name: "sue",
    gender: "female",
    children: [
      {
        id: "1",
        name: "larry"
      }
    ]
  }
];

// Person selection list
const persons = map(test, partialRight(pick, ["id", "name", "gender"]));
// Replace selected person value in `persons[0]`.
const childrens = find(test, item => item.id === persons[0].id).children;