简体   繁体   中英

Converting an Object of Arrays into Objects of Objects

Currently my data looks like this

{
    numberOne: [{
        timestamp: 3829383,
        value: 20323.23
    }],
    numberTwo: [{
        timestamp: 2382342,
        value: 120912.1
    }]
    ...
}

And I want to get it into this format

{
    numberOne: {
        timestamp: 3829383,
        value: 20323.23
    },
    numberTwo: {
        timestamp: 2382342,
        value: 120912.1
    }
    ...
}

I've tried Object.assign , .map() , .filter() ... nothing seems to work!

Any thoughts on how I could make this work would be very helpful

You can transform the input object by using Object.entries() , .reduce() and some Array Destructuring into the desired output:

 const data = { numberOne: [{ timestamp: 3829383, value: 20323.23 }], numberTwo: [{ timestamp: 2382342, value: 120912.1 }] }; const result = Object.entries(data) .reduce((r, [k, [v]]) => (r[k] = v, r), {}); console.log(result);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

You can use a for (var key in obj) loop and set the desired value for each key:

 var obj = { numberOne: [{ timestamp: 3829383, value: 20323.23 }], numberTwo: [{ timestamp: 2382342, value: 120912.1 }] }; console.log("Before -->", obj); for (var key in obj) { obj[key] = obj[key][0]; // take item 0 from each array } console.log("After -->", obj);

Enumerate the entries in the object, pull out the first item in each array and create an object with the key and the item.

 const data = { numberOne: [{ timestamp: 3829383, value: 20323.23 }], numberTwo: [{ timestamp: 2382342, value: 120912.1 }] } const transform = (arr) => Object.entries(arr).reduce((acc,[k,[v]]) => (acc[k] = v, acc), {}) console.log(transform(data))

Or, you can use Object.fromEntries :

 const data = { numberOne: [{ timestamp: 3829383, value: 20323.23 }], numberTwo: [{ timestamp: 2382342, value: 120912.1 }] } const transform = (arr) => Object.fromEntries(Object.entries(arr).map(([k,[v]]) => [k, v])) console.log(transform(data))

You can rebuild the object using reduce to iterate over the Object.entries (which gives you an array of a key and value):

 const data = { numberOne: [{ timestamp: 3829383, value: 20323.23 }], numberTwo: [{ timestamp: 2382342, value: 120912.1 }] } // Grab the entries and iterate over each // destructuring out the key and value from the array const out = Object.entries(data).reduce((acc, [key, value]) => { // Set the key on the initial object (acc), and set // the value to be the first element of the value array acc[key] = value[0]; // Return the initial object (acc) for the next iteration return acc; }, {}); console.log(out);

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