简体   繁体   English

Javascript Object into array将对象属性名称移动到数组键中

[英]Javascript Object into array move object property name into array key

I have this nested objects: 我有这个嵌套对象:

"State Names": {
    "State Cities": {
        "Los Angeles": {
            "about": "story",
            "zip": "91721"
        },
    }
}

and I was trying to make it look like this: 而我试图让它看起来像这样:

state: {
    city: [
        "name": "Los Angeles",
        "about": "story",
        "zip": "91721"
    ]
}

I've tried below code: 我试过下面的代码:

    var o = {
        "State Names": {
            "State Cities": {
                "Los Angeles": {
                    "about": "story",
                    "zip": "91721"
                },
            }
        }
    }
    var v = o["State Names"];
    var z = v["State Cities"];
    const result = Object.keys(z).map(i => z[i]);

    const state = {
        city: [...result]
    }
    this.setState({
        state
    })

But my result doesn't showing city names, only showing about and zip. 但我的结果并没有显示城市名称,只显示了约和拉链。 How do I include object key name into array as property during the map function? 如何在map函数中将对象键名称作为属性包含在数组中?

Use object spread (or Object.assign() ) to clone the city object, and add a name property: 使用object spread (或Object.assign() )克隆城市对象,并添加name属性:

 const o = {"State Names":{"State Cities":{"Los Angeles":{"about":"story","zip":"91721"}}}}; const cities = o['State Names']['State Cities']; const result = Object.keys(cities).map(name => ({ ...cities[name], name })); const state = { city: [...result] }; console.log(state); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM