从嵌套对象获取一些数据

时间:2019-04-03 12:55:58

标签: javascript ecmascript-6

我有这个嵌套对象(json):

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

该对象具有两个主要属性:applicationcategories

我想映射到application的{​​{1}}数组上,并获取cats数组的每个元素的name属性。

所以最终结果应该像这样:

cats

我尝试使用{ "App1": "FirstCategory", "App2": "ThirdCategory", "App3": "FirstCategory, ThirdCategory" } 函数,但是主要困难在于map属性applicaiton内部是数组(可以有多个值)。所以下面的代码不起作用:

cats

3 个答案:

答案 0 :(得分:2)

您可以使用Array.reduce来解决问题。

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:您可以引用this gist来安全地读取嵌套对象。

答案 1 :(得分:1)

尝试一下。

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

答案 2 :(得分:1)

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. 遍历应用程序的密钥
  2. 对于汽车上的每个按键环,以及对于每个猫,返回类别中的字符串值
  3. 加入猫串列表