本文介绍了使对象键成为等效子对象中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个复杂的对象,其中每个对象属性的键实际上应该是一个值.因此,我正在尝试将其转换为:

I have a complex object where the key of each object property should actually be a value. So, I am trying to convert this:

{
  "2019-04-24T00:00:00Z": {
    "one": 185,
  },
  "2019-04-25T00:00:00Z": {
    "one": 207,
  }
}

对此:

{
  {
    "date": "2019-04-24T00:00:00Z",
    "one": 185,
  },
  {
    "date": "2019-04-25T00:00:00Z",
    "one": 207,
  }
}

我尝试粘贴了一段代码.

I have pasted a snippet with an attempt.

var obj2 = {"all":[{"branches":[{"branchname":"NAN","mains":[{"mainName":"FirstOne","plName":[{"metrics":{"2019-04-24T00:00:00Z":{"one":185,"two":143697,"three":126161,"four":3909,"five":0,"six":0.2304,"seven":30.72,"eight":13.333,"nine":1.165},"2019-04-25T00:00:00Z":{"one":207,"two":50819,"three":16428,"four":2820,"five":0,"six":0.329,"seven":57.166,"eight":15.442,"nine":1.422}}}]}]}]}]};

var json2 = jsonPath(obj2, "$.all..branches..mains..[*].plName[*].metrics.");

var found = Object.keys(json2).find(function(layerKey) {
  console.log(json2[layerKey]);
});

for (var i = 0; i<= Object.keys(json2).length; i++) {
  for (var prop in json2[i]) {
    console.log("Key:" + prop);
    //Add date as a value in the JSON
    //json2[i].map(i=>i.Date=prop);
    json2[i]["Date"] = prop;
  }
}

//json2.map(i=>i.Date=prop);
console.log(json2);
<script src="https://www.w3resource.com/JSON/jsonpath.js"></script>

推荐答案

您可以尝试使用嵌套的map

You can try using nested map

var obj2 = {"all":[{"branches":[{"branchname":"NAN","mains":[{"mainName":"FirstOne","plName":[{"metrics":{"2019-04-24T00:00:00Z":{"one":185,"two":143697,"three":126161,"four":3909,"five":0,"six":0.2304,"seven":30.72,"eight":13.333,"nine":1.165},"2019-04-25T00:00:00Z":{"one":207,"two":50819,"three":16428,"four":2820,"five":0,"six":0.329,"seven":57.166,"eight":15.442,"nine":1.422}}}]}]}]}]};

var json2 = jsonPath(obj2, "$.all..branches..mains..[*].plName[*].metrics");

var result = json2.map(e =>
  Object.keys(e).map(m => Object.assign(e[m], {
    data: m
  }))
)

console.log(result)
<script src="https://www.w3resource.com/JSON/jsonpath.js"></script>

这篇关于使对象键成为等效子对象中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-04 23:11