我的密钥值对的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);
答案 0 :(得分:1)
您想要的数组长度是countByView
的键数的一半。使用长度,您可以生成带有for循环的有序数组或Array#from:
const countByView = {"count1":"0","count2":"230","count3":"246","count4":"172","view1":"2017","view2":"2018","view3":"2019","view4":"2020"}
const length = Object.keys(countByView).length / 2
const result = Array.from({ length }, (_, i) => ({
count: countByView[`count${i + 1}`],
view: countByView[`view${i + 1}`]
}))
console.log(result)

答案 1 :(得分:1)
您可以对具有数字的相同命名对象使用哈希表。
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);
答案 2 :(得分:0)
您可以简单地遍历该json对象的Object.keys
并添加一些逻辑来获取该结构。
let countByView= {
"count1": "0",
"count2": "230",
"count3": "246",
"count4": "172",
"view1": "2017",
"view2": "2018",
"view3": "2019",
"view4": "2020"
};
var keys = Object.keys(countByView);
var resArray = [];
for(var i=0; i<keys.length; i++){
var key = keys[i];
var obj = {};
if(key.indexOf('count') !== -1){
obj[key] = countByView[key];
obj['view'+(i+1)] = countByView['view'+(i+1)];
resArray.push(obj);
}
}
console.log(resArray);
&#13;
答案 3 :(得分:0)
您的示例包含以索引结尾的标签。您还没有指定它是否总是1,2 ......或者它可以是任何数字。在我的下面的代码中,我假设它可以是任何数字(只要 count 和 view 具有相同的数字)。
let countByView= {
"count1": "0",
"count2": "230",
"count3": "246",
"count4": "172",
"view1": "2017",
"view2": "2018",
"view3": "2019",
"view4": "2020"
}
function transform(input) {
return Object
.keys(input)
.filter( key => key.indexOf('count') === 0)
.reduce(
(list, key) => {
// Using a regexp to split the key into name and index.
let item = /^([a-z]+)([0-9]+)$/.exec(key);
if (!item) return console.warn('illegal key', key);
let index = item[2];
// push the data to the list, also converts the value to a number.
list.push({
count : input['count' + index ],
view : +input['view' + index ]
})
return list;
},[]
);
}
console.log(transform(countByView));
&#13;