gpt4 book ai didi

javascript - 将键值对转换为所需对象的数组

转载 作者:行者123 更新时间:2023-12-01 02:30:00 26 4
gpt4 key购买 nike

我有一个 JSON,其键值对为:

      let countByView= {
"count1": "0",
"count2": "230",
"count3": "246",
"count4": "172",
"view1": "2017",
"view2": "2018",
"view3": "2019",
"view4": "2020"
}

我想变成它

 let countByView=
[
{
"count1": 0,
"view1": 2017
},
{
"count1": 230,
"view1": 2018
},
{
"count1": 246,
"view1": 2019
},
{
"count1": 172,
"view1": 2020
}
]

我尝试使用下面的代码,但没有得到预期的结果,因为我无法正确转换。请让我知道是否有更好的解决方案..

  let result = Object.keys(countByView).map(e => {
let ret = {};
ret[e] = obj[e];
return ret;
});

console.log(result);

最佳答案

您可以对具有数字的同名对象使用哈希表。

var countByView = { count1: "0", count2: "230", count3: "246", count4: "172", view1: "2017", view2: "2018", view3: "2019", view4: "2020" },
hash = Object.create(null),
result = Object.keys(countByView).reduce(function (r, k) {
var [ , key, value] = k.match(/^(\D+)(\d+)$/);
if (!hash[value]) {
r.push(hash[value] = {});
}
hash[value][key] = countByView[k];
return r;
}, []);

console.log(result);

关于javascript - 将键值对转换为所需对象的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48376185/

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