首页 > 解决方案 > 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"
};

标签: javascriptarraysangularobject

解决方案


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()(检查在另一个答案中共享的片段)获得相同的结果。


推荐阅读