Skip to content

Instantly share code, notes, and snippets.

@bagaskarala
Last active December 1, 2022 08:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bagaskarala/157d4bac51a2b26eba80abf47f77165f to your computer and use it in GitHub Desktop.
Save bagaskarala/157d4bac51a2b26eba80abf47f77165f to your computer and use it in GitHub Desktop.
Get nested object value in javascript or JSON
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