Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
42
rated 0 times [  46] [ 4]  / answers: 1 / hits: 49433  / 9 Years ago, wed, august 19, 2015, 12:00:00

I'm about to use forOwn to iterate through an object's properties and create an array manually and can't helping thinking there's a oneliner already available to do it.



{ 
prop1 : value,
prop2: { sub:1}
}


to:



[ 
{key: prop1, value: value},
{key: prop2, value: {sub:1}}
]


Thanks


More From » lodash

 Answers
14

You can use lodash's _.map() with shorthand property names:





const obj = { 
prop1 : value,
prop2: { sub:1}
};

const result = _.map(obj, (value, prop) => ({ prop, value }));

console.log(result);

<script src=https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js></script>





Or you can do it using Object#entries with Array.map() and array destructuring:





const obj = { 
prop1 : value,
prop2: { sub:1}
};

const result = Object.entries(obj).map(([prop, value]) => ({ prop, value }));

console.log(result);




[#65363] Monday, August 17, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dylan

Total Points: 734
Total Questions: 91
Total Answers: 102

Location: Philippines
Member since Sat, Jul 11, 2020
4 Years ago
;