简体   繁体   中英

Filter an object with key and value pair with an array using javascript

I have an schema of data as

let data = [{
    "Count": {
        "Grapes": 1,
        "Banana": 6,
    }
}]

i need to filter through the object "Count" of data from an array "result"

let result = ["Banana"]

and get an output as

let output = {"Banana": 6}

How will i achieve this using javascript I have tried

let output = data[0]["Count"].filter( i => result.includes( data[0]["Count"] ));

This one liner:

const filtered = Object.fromEntries(Object.entries(data[0]["Count"]).filter(([k]) => result.includes(k))) 

With ES5 support:

const filtered  = Object.keys(data[0]["Count"]).filter(k => result.includes(k)).reduce((acc, k) => (acc[k] = data[0]["Count"][k], acc), {})

Demo:

 let data = [{ "Count": { "Grapes": 1, "Banana": 6, } }] let result = ["Banana"] const filtered = Object.fromEntries(Object.entries(data[0]["Count"]).filter(([k]) => result.includes(k))) const filteredES5 = Object.keys(data[0]["Count"]).filter(k => result.includes(k)).reduce((acc, k) => {acc[k] = data[0]["Count"][k]; return acc}, {}) console.log(filtered); console.log(filteredES5);

This would work for your values:

result.map(item => data[0].Count[item])

If you want key value and remove the undefined values as well:

result.map(item =>{return  data[0].Count[item] ? {[item] : data[0].Count[item]} : undefined} ).filter(item => item != undefined)

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