3

I’ve got an object having this form:

const obj = {
    abc: "Moon",
    def: "Earth",
    asd: "Sun",
    dmg: "Venus",
    xyz: "Mars",
    tuv: "Jupiter"
};

And an array with this form:

const arr = ["abc", "def", "tuv"];

I want to filter obj based on the values given in arr. That means, is there a way, probably using the filter method, to turn obj into this:

const newObj = {
    abc: "Moon",
    def: "Earth",
    tuv: "Jupiter"
};
georg
  • 211,518
  • 52
  • 313
  • 390
Kalaschnik
  • 769
  • 1
  • 7
  • 21

2 Answers2

7

You could map new objects with wanted properties and assign all to a single object.

const
    object = { abc: "Moon", def: "Earth", asd: "Sun", dmg: "Venus", xyz: "Mars", tuv: "Jupiter" },
    array = ["abc", "def", "tuv"],
    result = Object.assign(...array.map(k => ({ [k]: object[k] })));

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
6

You can use .reduce() to create the resultant object:

const arr = ["abc", "def", "tuv"];
const obj = {
    abc: "Moon",
    def: "Earth",
    asd: "Sun",
    dmg: "Venus",
    xyz: "Mars",
    tuv: "Jupiter"
};

const result = arr.reduce((r, c) => (r[c] = obj[c], r), {});

console.log(result);
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95