在JavaScript中深层嵌套的对象中获取对象的完整路径

时间:2019-03-29 11:32:05

标签: javascript ecmascript-6

我的源数组如下:

    arr =[
  {
    "dimensionId": 1,
    "dimensionName": "dimensionName1",
    "components": [
      {
        "componentId": 1,
        "componentName": "componentName1",
        "indicators": [
          {
            "indicatorId": 1,
            "indicatorName": "indicatorName1"
          },
          {...}
        ]
      },
       {...}
    ]
  },
  {...}
];

当我尝试使用.filter和.map通过'indicatorId'搜索最深层嵌套的对象时,它将返回如下对象:

{
            "indicatorId": 1,
            "indicatorName": "indicatorName1"
}

我需要做的是在遍历父母的孩子时也跟踪父母的属性。所需的输出将是这样的:

{
  "dimensionId": 1,
  "dimensionName": "dimensionName1",
  "componentId": 1,
  "componentName": "componentName2",
  "indicatorId": 1,
  "indicatorName": "indicatorName3"
}

是否可以递归地执行此操作?  编辑:ID在整个数组中不是唯一的

2 个答案:

答案 0 :(得分:1)

您可以将索引添加到形成相同数组的键中,并为每个嵌套数组返回一个新对象。

function getFlat(array) {
    return array.reduce((r, o, i) => {
        Object
            .entries(o)
            .forEach(([k, v]) => Object.assign(r, Array.isArray(v)
                ? getFlat(v)
                : { [[k, i].join('_')]: v }
            ));
        return r;
    }, {});
}

var data = [{ dimensionId: 1, dimensionName: "dimensionName1", components: [{ componentId: 2, componentName: "componentName2", indicators: [{ indicatorId: 3, indicatorName: "indicatorName3" }, { indicatorId: 4, indicatorName: "indicatorName4" }] }, { componentId: 5, componentName: "componentName5", indicators: [{ indicatorId: 6, indicatorName: "indicatorName6" }, { indicatorId: 7, indicatorName: "indicatorName8" }] }] }];

console.log(getFlat(data));
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

您可以循环查找,找到后返回。

arr =[
  {
    "dimensionId": 1,
    "dimensionName": "dimensionName1",
    "components": [
      {
        "componentId": 2,
        "componentName": "componentName2",
        "indicators": [
          {
            "indicatorId": 3,
            "indicatorName": "indicatorName3"
          },
					{
            "indicatorId": 3.1,
            "indicatorName": "indicatorName31"
          },
        ]
      }
    ]
  },
];

let out =  {}
arr.forEach(({dimensionId, dimensionName, components}) => {
	components.forEach(({indicators, componentId, componentName}) => {
		let found = indicators.find(({indicatorId}) => indicatorId === 3);
		if (found) {
			out = {dimensionId, dimensionName, componentId, componentName, ...found};
			return;
		}
	});
})

console.log(out)