简体   繁体   中英

Convert 2D array to assigned key Object

array = [
    ["Work", 11.0],
    ["Eat", 2.0],
    ["Commute", 2.0],
    ["Watch Tv", 2.0],
    ["Sleep", 7.0]
];

May I know how to convert the array to object:

var data = [{
        "Task": "Work",
        "Hour": 11.0
    },
    {
        "Task": "Eat",
        "Hour": 2.0
    }, {
        "Task": "Commute",
        "Hour": 2.0
    }, {
        "Task": "Watch Tv",
        "Hour": 2.0
    }, {
        "Task": "Sleep",
        "Hour": 7.0
    },
]

Array.prototype.map will create a new array based on a transformation of each element. The transformation you should apply is to create an object where the Task property is element [0] of the array item and the Hour property is the element [1] of the array item.

 array = [ ["Work", 11.0], ["Eat", 2.0], ["Commute", 2.0], ["Watch Tv", 2.0], ["Sleep", 7.0] ]; result = array.map(e => ({ Task: e[0], Hour: e[1] })); console.log(result);

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