简体   繁体   中英

Extract keys and values from object via an array of strings in javascript

I have some api data that is being returned as an object:

    {
        "name": "Luke Skywalker",
        "height": "172",
        "mass": "77",
        "hair_color": "blond",
        "skin_color": "fair",
        "eye_color": "blue",
        "birth_year": "19BBY",
        "gender": "male"
}

I have a list of keys in a configuration array that I am interested to extract from the original response:

let attributes = ['name', 'height', 'mass'];

How do i use the attribute array to give me an object back like so:

{
        "name": "Luke Skywalker",
        "height": "172",
        "mass": "77"
}

You can just loop over your array:

 const obj = { "name": "Luke Skywalker", "height": "172", "mass": "77", "hair_color": "blond", "skin_color": "fair", "eye_color": "blue", "birth_year": "19BBY", "gender": "male" }; let attributes = ['name', 'height', 'mass']; function buildObject(arr, obj) { const res = {}; arr.forEach(item => res[item] = obj[item]) return res } console.log(buildObject(attributes, obj))

Using reduce will be simplified.

 const update = (data, attrs) => attrs.reduce((acc, attr) => (acc[attr] = data[attr], acc), {}); const data = { name: "Luke Skywalker", height: "172", mass: "77", hair_color: "blond", skin_color: "fair", eye_color: "blue", birth_year: "19BBY", gender: "male" }; let attributes = ["name", "height", "mass"]; console.log(update(data, attributes));

You could use Object.entries method.

 let obj = { "name": "Luke Skywalker", "height": "172", "mass": "77", "hair_color": "blond", "skin_color": "fair", "eye_color": "blue", "birth_year": "19BBY", "gender": "male" }; let attributes = ['name', 'height', 'mass']; let picked = Object.fromEntries( attributes.map(att => [att, obj[att]]) ) console.log(picked);

You can use the function reduce for building the desired object.

 let obj = {"name": "Luke Skywalker","height": "172","mass": "77","hair_color": "blond","skin_color": "fair","eye_color": "blue","birth_year": "19BBY","gender": "male"}, attributes = ['name', 'height', 'mass'], {result} = attributes.reduce((a, c) => (Object.assign(a.result, {[c]: a.source[c]}), a), {result: Object.create(null), source: obj}); console.log(result);

You could map the wanted key along with their values and build a new object from it with Object.fromEntries .

 let obj = { name: "Luke Skywalker", height: "172", mass: "77", hair_color: "blond", skin_color: "fair", eye_color: "blue", birth_year: "19BBY", gender: "male" }, attributes = ['name', 'height', 'mass'], picked = Object.fromEntries(attributes.map(k => [k, obj[k]])); console.log(picked);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM