Simeon Lazarov
Simeon Lazarov

Reputation: 129

If object has specific properties create a new object only with them

As always I will explain my problem by example (that I solved but its a lot of code and its ugly, that's why I'm looking for a better solution). I'm trying to look at an object like this:

const object1 = {
  a: {a:1},
  b: 2,
  c: 3,
  d: 4,
};

I want to check if this object has any of the following properties [a,f] and if have one of them to create a new object with these properties

const object2 = {
  a: {a:1},
};

Upvotes: 0

Views: 39

Answers (3)

urchmaney
urchmaney

Reputation: 618

  const d = ['a', 'f', 'd']
  const object1 = {
    a: {a:1},
    b: 2,
    c: 3,
    d: 4,
  };

  const object2 = d.reduce((acc, ele) => {
    if(object1[ele] !== undefined) acc[ele] =   object1[ele]; 
  return acc;
  }, {});
  console.log(object2);

Upvotes: 1

Robin
Robin

Reputation: 5427

const object1 = {
  a: {a:1},
  b: 2,
  c: 3,
  d: 4,
}

const arrOfItem = ['a', 'd']
const newObj = {}

for(let item in object1) {
    if(arrOfItem.includes(item)) {
        newObj[item]= object1[item]
    }
}

console.log(newObj)

Upvotes: 1

Akash Sarode
Akash Sarode

Reputation: 447

see if this works for you,

function makeObject (properties) {
  const originalObject = {
    a: {a:1},
    b: 2,
    c: 3,
    d: 4,
  };
  let newObject = {}

  properties.forEach(property => {
    if(originalObject.hasOwnProperty(property)) {
      newObject[property] = originalObject[property];
    }
  });

  return newObject;
}

pass the properties as an array of strings to makeObject function

Upvotes: 1

Related Questions