Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a new object that only contains the key/value pairs specified in an array?

Tags:

javascript

I want to pass a function an array of keys and an object, and return a new object that only contains the key/value pairs that I specify in the keys array.

So if I had an object like this:

{"name" : "John Smith", "position" : "CEO", "year" : "2019" }

And I passed the array

["name", "year"]

the new object returned would be:

{"name" : "John Smith", "year" : "2019" }

I've been playing around with it, but my code is not working.

function parse(keys, data) {
    let obj = JSON.parse(data);

    let newObj = {};

    keys.array.forEach(element => {
        newObj[element] = obj.element;
    });

    return newObj;
};
like image 217
CastleCorp Avatar asked Dec 23 '25 00:12

CastleCorp


2 Answers

You dont need to do parse.Secondly this line keys.array.forEach is wrong. This is because there is no array key inside keys.Also replace obj.element; with data[element]

let data = {
  "name": "John Smith",
  "position": "CEO",
  "year": "2019"
}
let keys = ["name", "year"]


function parse(keys, data) {
  let newJson = {};
  keys.forEach(element => {
    newJson[element] = data[element];
  });

  return newJson;
};

console.log(parse(keys, data))
like image 135
brk Avatar answered Dec 24 '25 13:12

brk


One way to achieve this would be through filtering an array of object entries:

const entries = Object.entries({
  "name" : "John Smith",
  "position" : "CEO",
  "year" : "2019"
})

entries contains:

[
  [
    "name",
    "John Smith"
  ],
  [
    "position",
    "CEO"
  ],
  [
    "year",
    "2019"
  ]
]

Filtering out keys:

const filteredEntries = entries.filter(([ key ]) => ["name", "year"].includes(key))

filteredEntries contains:

[
  [
    "name",
    "John Smith"
  ],
  [
    "year",
    "2019"
  ]
]

Last step - construct an object:

const filteredObject = Object.fromEntries(filteredEntries)

filteredObject contains:

{
  "name": "John Smith",
  "year": "2019"
}

Putting it together as a function:

function filterObjectByGivenKeys(object, keys) {
  const filteredEntries = Object
    .entries(object)
    .filter(([ key ]) => keys.includes(key))

  return Object.fromEntries(filteredEntries)
}

Or, if we prefer reduce and more terse syntax:

const filterObjectByGivenKeys = (object, keys) =>
  Object.entries(object)
    .filter(([ key ]) => keys.includes(key))
    .reduce((obj, [key, value]) => ({ ...obj, [key]: value }), {})
like image 33
Pavel Ye Avatar answered Dec 24 '25 14:12

Pavel Ye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!