Last active
December 1, 2022 08:34
-
-
Save bagaskarala/157d4bac51a2b26eba80abf47f77165f to your computer and use it in GitHub Desktop.
Get nested object value in javascript or JSON
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const getValue = (path, obj) => { | |
const newPath = path.replace(/\]/g, ''); | |
const arrayPath = newPath.split(/[\[\.]+/) || newPath; | |
return arrayPath.reduce((obj, k) => (obj ? obj[k] : obj), obj); | |
}; | |
const doFilterObject = (rawData, filterKey) => | |
filterKey.reduce((acc, cur) => { | |
const isNested = new RegExp(/\[|\./, 'g').test(cur); | |
const newData = isNested ? getValue(cur, rawData) : rawData[cur]; | |
acc = { ...acc, [cur]: newData }; | |
return acc; | |
}, {}); | |
// example data | |
const data = { | |
id: 123123, | |
service: 'fast_logistic', | |
address: { | |
sender: { city: 'yogyakarta', postalCode: 55511 }, | |
receiver: { city: 'jakarta', postalCode: 59888 }, | |
}, | |
items: [ | |
{ name: 'phone', description: 'to make a call' }, | |
{ name: 'laptop', description: 'to work' }, | |
], | |
}; | |
const filterKey = ['id', 'address.sender.city', 'items[0].description']; | |
// result | |
const result = doFilterObject(data, filterKey); | |
console.log(result); // {id: 123123, address.sender.city: "yogyakarta", items[0].description: "to make a call"} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment