简体   繁体   中英

NodeJS - Extract data from a multilevel array of objects

I have the following JSON array :

{
"list": [{
    "name": "Assignment",
    "id": 67,
    "template": 0,
    "children": [{
        "assignmentnumber": 1000,
        "fromCountry": "Sweden",
        "toCountry": "Spain",
        "fromCity": "Stockholm",
        "toCity": "Madrid"
    }, {
        "assignmentnumber": 15678,
        "fromCountry": "Sweden",
        "toCountry": "Germany",
        "fromCity": "Stockholm",
        "toCity": "Berlin"
    }, {
        "assignmentnumber": 10001,
        "fromCountry": "Sweden",
        "toCountry": "United Kingdom",
        "fromCity": "Stockholm",
        "toCity": "London"
    }]
}, {
    "name": "Valuation form",
    "id": 36,
    "template": 0,
    "children": [15678]
}, {
    "name": "Claim",
    "id": 12,
    "template": 0,
    "children": [1000, 10001]
}]
}

I need to extract a new array from the array containing only the 'name' element. I have tried lodash but cannot figure out how to use it properly.

Anyone who can give me a clue how to do this ?

You should use map method, which accepts as parameter a callback function.

The map() method creates a new array with the results of calling a provided function on every element in this array.

var array=obj.list.map(callback);
function callback(item){
    return item.name;
}

Or simply:

var array=obj.list.map(el=>el.name);

 var obj={ "list": [{ "name": "Assignment", "id": 67, "template": 0, "children": [{ "assignmentnumber": 1000, "fromCountry": "Sweden", "toCountry": "Spain", "fromCity": "Stockholm", "toCity": "Madrid" }, { "assignmentnumber": 15678, "fromCountry": "Sweden", "toCountry": "Germany", "fromCity": "Stockholm", "toCity": "Berlin" }, { "assignmentnumber": 10001, "fromCountry": "Sweden", "toCountry": "United Kingdom", "fromCity": "Stockholm", "toCity": "London" }] }, { "name": "Valuation form", "id": 36, "template": 0, "children": [15678] }, { "name": "Claim", "id": 12, "template": 0, "children": [1000, 10001] }] }; console.log(obj.list.map(function(item){ return item.name; })); 

You can do this without lodash, using native Array APIs.

const obj = { /* The JSON in your question */ };
const names = obj.list.map(item => item.name);

Array.map() takes a function and calls that function on each item of an array, returning a new array containing the result of each item.

Map is the best way to go as everyone else stated. Another alternative is use a forEach loop, specially if you want to operate with them.

var children = obj.children;
var array_of_names;

children.forEach(function (item)){
    array_of_names.push(item.name);
    //... Do more operations for each item
}

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