首页 > 解决方案 > Lodash 从选定的键创建新数组

问题描述

我的道具数据输出为:

const { profile } = this.props;
console.log("help", profile);

{notes: "", name: "John", gender: "M", dob: "", age: "33", nationality: "British", notes2: "no notes", notes3: "no notes"}

我希望能够抽出笔记并最终得到如下内容:

{notes: "", notes2: "no notes", notes3: "no notes"}

我需要将“配置文件”作为自己的道具,因此需要创建一个 const 来存储此输出。

我试过这样的事情:

const oldArray = _.map(_.toPairs(profile), d => _.fromPairs([d]));
const newArray = _.map(oldArray => [{notes: notes}, {notes: notes2}, {notes: notes3}]);

我想这样做的原因是然后运行检查以查看所有音符是否为空,但是当它们位于具有许多不同键的数组中时不能这样做。

标签: javascriptreactjslodash

解决方案


如果你有一个对象,你可以使用_.pick方法并返回一个具有特定属性的新对象。

const obj = {notes: "", name: "John", gender: "M", dob: "", age: "33", nationality: "British", notes2: "no notes", notes3: "no notes"}
const notes = _.pick(obj, ['notes', 'notes2', 'notes3']);
console.log(notes)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>


推荐阅读