1

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?

0

1 Answer 1

4

Use object spread (or Object.assign()) to clone the city object, and add a name property:

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.