Convert object to an array of objects?

前端 未结 3 1464
无人共我
无人共我 2021-01-13 15:30

I have an object that looks like this:

{
  \"1\": \"Technology\",
  \"2\": \"Startup\",
  \"3\": \"IT\",
}

and I need to convert it to an a

相关标签:
3条回答
  • 2021-01-13 15:39

    Assuming your object instance is named obj:

    Object.keys(obj).reduce((acc, curr) => {
        return [...acc, { id: curr, name: obj[curr] }]
    }, [])
    
    0 讨论(0)
  • 2021-01-13 15:48

    the trivial way

    var o = {
        "1": "Technology",
        "2": "Startup",
        "3": "IT",
    };
    var arr = [];
    for(var i in o) {
        arr.push({
            id: i,
            number: o[i]
        });
    };
    
    0 讨论(0)
  • 2021-01-13 15:54

    You can use .map() with Object.keys():

    let data = {
        "1": "Technology",
        "2": "Startup",
        "3": "IT",
    };
    
    let result = Object.keys(data)
                       .map(key => ({id: Number(key), name: data[key]}));
    
    console.log(result);

    Useful Resources:

    • Array.prototype.map()
    • Object.keys()
    0 讨论(0)
提交回复
热议问题