从嵌套对象数组中获取具有空值的对象

时间:2019-10-20 02:57:38

标签: javascript arrays object lodash

我有一个嵌套对象数组。如何仅使用对象数组中的特定键来获取具有空值的对象?

let headers = [{
    title: 'Arun',
    id: 'arunId',
    onClick: 'onClickArun'
  },
  {
    title: "George",
    id: 'georgeId',
    onClick: '',
    children: [{
        title: 'David',
        id: 'davidId',
        onClick: 'onClickDavid'
      },
      {
        title: 'Patrick',
        id: 'patrickId',
        onClick: 'onClickPatrick'
      }
    ]
  },
  {
    title: 'Mark',
    id: 'markId',
    onClick: 'onClickMark'
  }
]

const headersMap = ({
  onClick,
  children
}) => (onClick ? {
  onClick
} : _.map(children, headersMap));

const headersFlatMap = _.flatMap(headers, headersMap);

const headerObj = _.reduce(_.map(headersFlatMap, 'onClick'), (ac, a) => ({ ...ac,
  [a]: null
}), {});

console.log(headerObj)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

代码运行良好,但是有没有优化的方法?

预期输出:

{
  "onClickArun": null,
  "onClickDavid": null,
  "onClickPatrick": null,
  "onClickMark": null
}

任何帮助将不胜感激。谢谢。

2 个答案:

答案 0 :(得分:1)

headersMap中,您可以使用null{ [onClick]: null }创建对象。现在,您可以将对象数组散布到_.assign()中,以将它们转换为单个对象。

const headers = [{"title":"Arun","id":"arunId","onClick":"onClickArun"},{"title":"George","id":"georgeId","onClick":"","children":[{"title":"David","id":"davidId","onClick":"onClickDavid"},{"title":"Patrick","id":"patrickId","onClick":"onClickPatrick"}]},{"title":"Mark","id":"markId","onClick":"onClickMark"}];

const headersMap = ({ onClick, children }) =>
  onClick ? 
    { [onClick]: null } // create the object with a null value
    : 
    _.flatMap(children, headersMap); // use flatMap to handle multiple levels

const headerObj = _.assign({}, ..._.flatMap(headers, headersMap)); // spread and merge

console.log(headerObj)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

答案 1 :(得分:1)

您可以使用reduce方法创建递归函数,该函数将返回对象作为结果并在任意级别上搜索目标键。

let headers = [{"title":"Arun","id":"arunId","onClick":"onClickArun"},{"title":"George","id":"georgeId","onClick":"","children":[{"title":"David","id":"davidId","onClick":"onClickDavid"},{"title":"Patrick","id":"patrickId","onClick":"onClickPatrick"}]},{"title":"Mark","id":"markId","onClick":"onClickMark"}]

function get(prop, data) {
  return data.reduce((r, e) => {
    if (e[prop]) r[e[prop]] = null;
    if (e.children) Object.assign(r, get(prop, e.children))
    return r;
  }, {})
}

const result = get('onClick', headers)
console.log(result)