Destructure object properties from properties provided in an array

moctarjallo :

I need to make a function getPropertiesData(list) that takes a list of properties and an object containing those properties and only return properties of the object that match in the list.

Illustration:

function getPropertiesData(['x', 'y']){
    const o = {
        'x': 1, 
        'y': 2, 
        'z': 3
       }

    // Will return 
    return {
        'x': 1,
        'y': 2
       }
    // not including the 'z' variable since it was not specified as input in the list array
}

How to do that in javascript ?

palaѕн :

You can use Object.assign() method for this requirement like:

function getPropertiesData(arr) {
  const o = { 'x': 1, 'y': 2, 'z': 3 }
  return Object.assign({}, ...arr.map(a => ({[a]: o[a]})));
}

console.log(getPropertiesData(['x', 'y']))

In case you need to get values for only the keys which exists in the object o, you can use this:

function getPropertiesData(arr) {
  const o = { 'x': 1, 'y': 2, 'z': 3 }
  return Object.assign({}, ...arr.map(a => o.hasOwnProperty(a) ? ({[a]: o[a]}) : null));
}

console.log(getPropertiesData(['x', 'y']))
console.log(getPropertiesData(['w', 'x']))

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=220710&siteId=1