gpt4 book ai didi

javascript - 如何将此数组转换为对象数组?

转载 作者:行者123 更新时间:2023-11-30 12:03:02 25 4
gpt4 key购买 nike

这是我的数组:

[
['x', 1],
['y', 2],
['z', 3],
['F', "_180"],
['x', 1],
['y', 2],
['z', 3],
['t', 4]
['F', "_360"],
['x', 1],
['y', 2],
['z', 3],
['t', 4],
['m', 5]
['F', "_480"],
]

这是我想要实现的:

[{
profile_180: {
x: 1,
y: 2,
z: 3
}
}, {
profile_360: {
x: 1,
y: 2,
z: 3,
t: 4
}
}, {
profile_480: {
x: 1,
y: 2,
z: 3
t: 4,
m: 5
}
}]

我如何得到这个?

最佳答案

data = [
['x', 1],
['y', 2],
['z', 3],
['F', "_180"],
['x', 1],
['y', 2],
['z', 3],
['t', 4],
['F', "_360"],
['x', 1],
['y', 2],
['z', 3],
['t', 4],
['m', 5],
['F', "_480"],
];

var result = {};
var current = {};
data.forEach(function(row) {
if (row[0] == 'F') {
result['profile' + row[1]] = current;
current = {};
} else {
current[row[0]] = row[1];
}
});
console.log(result);
<!-- results pane console output; see http://meta.stackexchange.com/a/242491 -->
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

关于javascript - 如何将此数组转换为对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36147163/

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