简体   繁体   中英

Converting nested arrays to objects

[["seller" , [["id" , "1"], ["name", "test"]]], ["token", "aasfgsgd"], ["settings", [["general", false], ["store", [["trusted", true], ["socialMedia", [["fbConnected", true], ["igConnected", false]]]]]]]]

This nested array can be variable, So convert it into an Object like shown below

{
    "seller": {
    "id": 1,
    "name": "test"
    },
    "token": "aasfgsgd",
    "settings": {
        "general": false,
        "store": {
            "trusted": true,
            "socialMedia": {
                "fbConnected": true,
                "igConnected": false
            }
        }
    }
}

You can use Object.fromEntries() with a recursive function to convert all nested [[key, value], ...] pair arrays into objects themselves.

The Object.fromEntries() method is able to take an array such as:

[["key", "val2"]]

... and convert it into an object:

{
  "key": "val2"
}

However, if "val2" is an array itself, this would need to be converted into an object first. This can be done by recursively calling Object.fromEntries() on the value entries which are arrays.

See example below:

 const arr = [["seller" , [["id" , 1], ["name", "test"]]], ["token", "aasfgsgd"], ["settings", [["general", false], ["store", [["trusted", true], ["socialMedia", [["fbConnected", true], ["igConnected", false]]]]]]]]; const makeObject = arr => { return Object.fromEntries(arr.map( ([key, val]) => Array.isArray(val) ? [key, makeObject(val)] : [key, val] )); } console.log(makeObject(arr));

A more browser-friendly approach would be to use .reduce() with the spread syntax instead of Object.fromEntries() :

 const arr = [["seller" , [["id" , 1], ["name", "test"]]], ["token", "aasfgsgd"], ["settings", [["general", false], ["store", [["trusted", true], ["socialMedia", [["fbConnected", true], ["igConnected", false]]]]]]]]; const makeObject = arr => { return arr.reduce((o, [key, val]) => { return Object.assign(o, {[key]: Array.isArray(val) ? makeObject(val) : val}); }, {}); } console.log(makeObject(arr));

 const array = [["seller" , [["id" , "1"], ["name", "test"]]], ["token", "aasfgsgd"], ["settings", [["general", false], ["store", [["trusted", true], ["socialMedia", [["fbConnected", true], ["igConnected", false]]]]]]]]; function objectify(arr) { return arr.reduce((acc, item) => { let builder; if (Array.isArray(item[0])) { builder = objectify(item[0]) } else { const propName = item[0]; const propValue = Array.isArray(item[1]) ? objectify(item[1]) : item[1]; builder = {[propName]: propValue}; } return { ...acc, ...builder } }, {}); } console.log(objectify(array));

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