0

I've been trying to create a dynamic function which could flatten an nested key/val object inside an array of objects

How do I get this structure? Knowing that i would like to call the keys dynamically and bind the parent key and child key with an _.

Input:

const list = [
    {
        month: 'Jan', 
        value: 20, 
        metric: { 
            name: 'Rice', 
            measurement: 'Kg', 
            is_currency: false 
        },
        entity: { 
            name: 'Rev', 
            type: 'limited company'
        }
    },
    {
        month: 'Jan', 
        value: 1000, 
        metric: { 
            name: 'Revenue', 
            measurement: 'Dollars', 
            is_currency: true
        },
        entity: { 
            name: 'Rev', 
            type: 'limited company'
        }
    },
]

Expected output:

const list = [
    {
        month: 'Jan', 
        value: 20, 
        metric_name: 'Rice',
        metric_measurement: 'Kg', 
        metric_currency: false,
        entity_name: 'Rev', 
        entity_type: 'limited company'
    },
    {
        month: 'Jan', 
        value: 1000, 
        metric_name: 'Revenue', 
        metric_measurement: 'Dollars', 
        metric_is_currency: true
        entity_name: 'Rev', 
        entity_type: 'limited company'
    },
]
th-hq
  • 57
  • 4
  • 1
    That sounds like a homework problem. – PHP Guru Apr 10 '20 at 16:53
  • 2
    Please show any attempt that you have made to solve this issue yourself. You are expected to have made an attempt that we can then help you debug. https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users Also review [ask] – Taplar Apr 10 '20 at 16:54
  • `const flatObj = (obj, keyPrefix = null) => Object.entries(obj).reduce((acc, [key, val]) => { if(typeof val !== 'object') { return { ...acc, [keyPrefix ? \`${keyPrefix}_${key}\`: key]: val } } else { return { ...acc, ...flatObj(val, keyPrefix ? \`${keyPrefix}_${key}\` : key) } } }, {})` `list.map(item => flatObj(item))` – David Apr 10 '20 at 17:13

0 Answers0