简体   繁体   中英

Unable to get object instead of array

Hello I am new to the site, and I have a problem with javascript that I do not know how to fix.

I have an array, which I want to turn into an object.

 arr = [ {prefer: "sport_swimming", rating: "1"}, {prefer: "sport_running", rating: "5"}, {prefer: "sport_tennis", rating: "2"}, {prefer: "study_archeology", rating: "4"}]; obj = Object.assign({}, arr); console.log(obj);

I want to get to something like this:

{
    "sport": {
        "swimming":"1",
        "running":"5",
        "tennis":"2"
    },
    "study":
    {
        "archeology":"4"
    }
}

Using reduce you can look over the array and build an object using the keys you split off the property.

 const arr = [ {prefer: "sport_swimming", rating: "1"}, {prefer: "sport_running", rating: "5"}, {prefer: "sport_tennis", rating: "2"}, {prefer: "study_archeology", rating: "4"} ]; const out = arr.reduce((acc, data) => { const parts = data.prefer.split("_"); acc[parts[0]] = acc[parts[0]] || {}; acc[parts[0]][parts[1]] = data.rating; return acc; }, {}); console.log(out);

You can use reduce :

 const arr = [ { prefer: "sport_swimming", rating: "1" }, { prefer: "sport_running", rating: "5" }, { prefer: "sport_tennis", rating: "2" }, { prefer: "study_archeology", rating: "4" }]; const result = arr.reduce((a, e) => ([parent, child] = e.prefer.split('_'), (a[parent]??= {})[child] = e.rating, a), {}); 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