javascript - How to filter an object by comparing with the elements of the arrays
问题描述
I have an array myarrays
and object obj
, I need to filter the object by comparing elements of array with the key of objects.
You can view this code on StackBlitz as well: https://stackblitz.com/edit/angular-uerzhk.
import { Component, OnInit } from "@angular/core";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
name = "Angular";
ngOnInit() {
const myarrays = ["createddate", "enddate"];
const obj = {
createddate: "30-01-02",
progressdate: "30-01-03",
enddate: "30-01-04"
};
}
}
The result of filtering obj
should be the following:
const filterarrayresult = {
createddate: "30-01-02",
enddate: "30-01-04"
};
解决方案
const myarrays = ["createddate", "enddate"];
const obj = {
createddate: "30-01-02",
progressdate: "30-01-03",
enddate: "30-01-04"
};
let filtered = Object.assign({},
...myarrays.map(prev => {
return {
[prev]: obj[prev]
};
})
);
console.log(filtered);
这可能不是一个优雅的解决方案,但它简单且有效。您也可以使用reduce()
(检查在另一个答案中共享的片段)获得相同的结果。
推荐阅读
- android - AdMob 在运行时出现间歇性 java.lang.NoClassDefFoundError
- salt-stack - salt 在后台执行哪些命令来实现所需的 minion 状态?
- java - 为什么我从数组 B 得到 0,但它在数组 A 上工作
- android - 是否可以通过 USB 集线器在两部安卓手机之间进行通信?
- d3.js - 更新 D3.js 树形图的数据
- c# - 使用 Entity Framework Core 进行表拆分。将表展平为主-详细信息
- python - python中的独立时间倒计时
- spring - Spring - 不持久记住我在应用程序重启时无法生存
- java - 如何从对象的 Arraylist 中获取子列表?
- macos - macOS High Sierra 10.13.6 上的一般编译问题