gpt4 book ai didi

javascript - 使对象键成为等效子对象中的值

转载 作者:行者123 更新时间:2023-11-28 11:44:05 25 4
gpt4 key购买 nike

我有一个复杂的对象,其中每个对象属性的键实际上应该是一个值。所以,我正在尝试转换它:

{
"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,
}
}

我尝试粘贴了一个片段。

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

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>

关于javascript - 使对象键成为等效子对象中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56775220/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com