简体   繁体   中英

transform object to array with parent child relationship in lodash

Is this possible in lodash or any other javascript/typescript way

var obj = {
    a: [ {id:1},{id:2},{id:3}]
    b: [ {id:4},{id:5},{id:6}]
    c: [ {id:7},{id:8},{id:9}]
}
// transform to 
var arr = [
{title:a, items:[{id:1},{id:2},{id:3}]},
{title:b, items: [ {id:4},{id:5},{id:6}]},
{title:c, items: [ id:7},{id:8},{id:9}]}
]

You can use Object.keys for that:

 var obj = { a: [ {id:1},{id:2},{id:3}], b: [ {id:4},{id:5},{id:6}], c: [ {id:7},{id:8},{id:9}] } var result = Object.keys(obj).map(function(key) { return { title: key, items: obj[key] } }) console.log(result); 

You can use a highly-readable one-liner for this with lodash and ES6:

_.map(obj, (items, title) => ({ title, items }));

You can completely avoid Object.keys() because map() works on objects. The callback function gets the object key and the value of that key as arguments. So, you can name them in such a way that allows for object literal shorthand notation, as we've done here with items and title .

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