Skip to content

Instantly share code, notes, and snippets.

@bagaskarala
Last active December 1, 2022 08:34
Show Gist options
  • Save bagaskarala/157d4bac51a2b26eba80abf47f77165f to your computer and use it in GitHub Desktop.
Save bagaskarala/157d4bac51a2b26eba80abf47f77165f to your computer and use it in GitHub Desktop.

Revisions

  1. bagaskarala revised this gist Dec 1, 2022. 1 changed file with 0 additions and 2 deletions.
    2 changes: 0 additions & 2 deletions readme.md
    Original file line number Diff line number Diff line change
    @@ -1,5 +1,3 @@
    Mapping nested value from JSON

    #### sandbox
    https://stackblitz.com/edit/js-nbdnkh?file=index.js

  2. bagaskarala revised this gist Dec 1, 2022. 1 changed file with 32 additions and 0 deletions.
    32 changes: 32 additions & 0 deletions index.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,32 @@
    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"}
  3. bagaskarala revised this gist Dec 1, 2022. 1 changed file with 2 additions and 0 deletions.
    2 changes: 2 additions & 0 deletions readme.md
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,5 @@
    Mapping nested value from JSON

    #### sandbox
    https://stackblitz.com/edit/js-nbdnkh?file=index.js

  4. bagaskarala created this gist Dec 1, 2022.
    5 changes: 5 additions & 0 deletions readme.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,5 @@
    #### sandbox
    https://stackblitz.com/edit/js-nbdnkh?file=index.js

    #### preview
    https://js-nbdnkh.stackblitz.io/