1

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 ?

moctarjallo
  • 1,479
  • 1
  • 16
  • 33

5 Answers5

2

You can use Object.entries to obtain an array of key/value pair arrays of an object. Next, filter the entries array by inclusion in the wantedKeys array. Finally, create an object from the selected pairs using Object.fromEntries.

const o = {a: 1, b: 2, c: 3};
const wantedKeys = ["a", "c"];

const selected = Object.fromEntries(
  Object.entries(o)
        .filter(([k, v]) => wantedKeys.includes(k))
);

console.log(selected);

This might be slow on large objects, so you can use map and filter to bind the complexity to the wantedKeys array.

If you're making this into a function, it doesn't make sense to hardcode the object. I'd add that as a parameter as well:

const pickFromObj = (o, wantedKeys) => Object.fromEntries(
  wantedKeys.filter(e => e in o)
            .map(e => [e, o[e]])
);

console.log(pickFromObj({a: 1, b: 2, c: 3}, ["a", "c"]));
ggorlen
  • 44,755
  • 7
  • 76
  • 106
2

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']))
palaѕн
  • 72,112
  • 17
  • 116
  • 136
2

Just create a new object by mapping the wanted key with the values.

function getPropertiesData(properties) {
    const o = { x: 1, y: 2, z: 3 };
    return Object.fromEntries(properties.map(k => [k, o[k]]));
}

console.log(getPropertiesData(['x', 'y']));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

You can do this by iterating over the key/value pairs in the object, and use the array reduce to isolate the ones you're looking for. Here, reduce builds a new object while iterating over all the object values.

const getPropertiesData = (obj, props) =>
  Object.entries(obj)
    .reduce((result, [key, value]) =>
      props.includes(key) ? {...result, [key]:value} : result
    , {})

You can then test it using your object, o:

const o = {
 'x': 1, 
 'y': 2, 
 'z': 3
}

console.log(getPropertiesData(o, ['x', 'y']))
Rob Brander
  • 3,702
  • 1
  • 20
  • 33
1

The function should accept an object, o, and properties array, props. Use Array.prototype.reduce on the input props to create a new output object using Object.assign.

const getProperties = (o = {}, props = []) =>
  props.reduce
    ( (r, k) => Object.assign(r, { [k]: o[k] })
    , {}
    )

const result =
  getProperties({ a: 1, b: 2, c: 3 }, [ 'a', 'b', 'z' ])

console.log(result)
// { a: 1, b: 2, z: undefined }
Guest
  • 11
  • 1