undefinedUser
undefinedUser

Reputation: 257

Get some data from nested object

I have this nested object (json):

const json = {
  "application": {
    "App1": {
      "cats": [
        1
      ]
    },
    "App2": {
      "cats": [
        3
      ]
    },
    "App3": {
      "cats": [
        1,
        2
      ]
    }
  },
  "categories": {
    "1": {
      "name": "FirstCategory"
    },
    "2": {
      "name": "SecondCategory"
    },
    "3": {
      "name": "ThirdCategory"
    }
  }
};

This object has two main properties: application and categories.

I want to map over application's cats array and get name property of each element of cats array.

So the final result should look like:

{
   "App1": "FirstCategory",
   "App2": "ThirdCategory",
   "App3": "FirstCategory, ThirdCategory"
}

I have tried to use map function, but the main difficulty is that inside applicaiton property cats is array (can have multiple values). So the code below didn't work:

Object.values(json.application).map(val => {
    Object.keys(json.categories).map(key => {
       //print something
    });
});

Upvotes: 0

Views: 65

Answers (3)

Ashish
Ashish

Reputation: 4330

You can use Array.reduce for an elegant solution.

const json = {
  "application": {
    "App1": {
      "cats": [
        1
      ]
    },
    "App2": {
      "cats": [
        3
      ]
    },
    "App3": {
      "cats": [
        1,
        2
      ]
    }
  },
  "categories": {
    "1": {
      "name": "FirstCategory"
    },
    "2": {
      "name": "SecondCategory"
    },
    "3": {
      "name": "ThirdCategory"
    }
  }
};

//Getting Application object
const application = json.application

//Getting Categories object
const categories = json.categories

//initializing reduce with a blank object and pushing all the keys of the application object
//Looping over keys of application object
const requiredOutput = Object.keys(application).reduce((out, appKey) => {
    //Setting value based on categories name
    out[appKey] = application[appKey].cats.map(id => categories[id].name)
    return out
}, {})

console.log(requiredOutput)

PS: You can refer this gist for safe reading from a nested object.

Upvotes: 2

chriss
chriss

Reputation: 669

const result = Object.keys(json.application).reduce((a,key) => {
    a[key] = json.application[key].cats
        .map(cat => json.categories[cat].name)
        .join(", ")
    return a;
}, {})
  1. loop over keys of application
  2. for each key loop over car, and for each cat return string value from category
  3. join list of cat strings

Upvotes: 1

Qellson
Qellson

Reputation: 552

Try it with this.

    for(let val in json.application){
      json.application[val] = json.application[val].cats.map(cat => json.categories[cat].name).join(",")
    }

Upvotes: 1

Related Questions