javascript - 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}]);
我想这样做的原因是然后运行检查以查看所有音符是否为空,但是当它们位于具有许多不同键的数组中时不能这样做。
解决方案
如果你有一个对象,你可以使用_.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>
推荐阅读
- python - 从第二个字典更新字典键和值
- angular - 在 Angular 7 拦截器中调用异步函数
- php - 消除城市 (PHP)
- android - Android Studio 中不允许迁移到 androidX
- centos - 我怎样才能创建一个centos yum public repo
- elasticsearch - 改善单元测试的弹性搜索启动时间的设置?
- javascript - 如何获取 javascript 函数来删除添加的待办事项?
- java - 等于并与 BigDecimal 比较
- amazon-web-services - 计划 RDS 仅在计划的 Fargate 任务运行时运行
- c++ - 尝试使用 enable_if 启用 SFINAE 时出现“无法重载”错误