gpt4 book ai didi

Javascript - 将大对象文字转换为另一个对象文字

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:08:43 24 4
gpt4 key购买 nike

我正在尝试将一个 Javascript 对象字面量转换为另一个。我认为有一些循环是可能的,但我无法完成它。目标结构如下所示,“convertedData”。

fiddle 可以在这里找到:http://jsbin.com/ajemih/9/edit

这是 JSON 数据:

var data =

{
"29-10-2012": {
"1a": {
"allMovement": "1",
"allLoad": "2",
"loadMovement": "3"
},
"1b": {
"allMovement": 4,
"allLoad": 5,
"loadMovement": 6
}
},
"22-02-2013": {
"1a": {
"allMovement": "7",
"allLoad": "8",
"loadMovement": "9"
},
"1b": {
"allMovement": "10",
"allLoad": "11",
"loadMovement": "12"
}
}
};

for (day in data) {

for (id in data[day]) {

document.write(data[day][id].allMovement+"<br>");
document.write(data[day][id].allLoad+"<br>");
document.write(data[day][id].loadMovement+"<br>");

}
}

/*

convertedData = [[1,7],
[2, 8],
[3, 9],
["4","10"],
["5","11"],
["6", "12"]];


convertedData = [["1a-allMovement-29-10-2012","1a-allMovement-22-02-2013],
["1a-allLoad-29-10-2012", "1a-allLoad22-02-2013"],
["1a-loadMovement-29-10-2012", "1a-loadMovement-22-02-2013"],
["1b-allMovement-29-10-2012","1a-allMovement-22-02-2013"],
["1b-allLoad-29-10-2012","1b-allLoad22-02-2013"],
["1b-loadMovement-29-10-2012", "1b-loadMovement-22-02-2013"]];

*/

最佳答案

尝试这样的事情,根据需要调整它:

var out = [],
dateKey, idx, item, itemKey, inner;

for (dateKey in data) {
if (data.hasOwnProperty(dateKey)) {
idx = out.length;
out[idx] = [];
item = data[dateKey];
for (itemKey in item) {
if (item.hasOwnProperty(itemKey)) {
inner = item[itemKey];
out[idx].push(itemKey + '-' + inner.allMovement + '-' + inner.allLoad + '-' + inner.loadMovement);
}
}
}
}
console.log(out);

关于Javascript - 将大对象文字转换为另一个对象文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15305426/

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