gpt4 book ai didi

javascript - 我有一个对象,我想要将对象与给定对象分开

转载 作者:行者123 更新时间:2023-12-01 02:05:07 24 4
gpt4 key购买 nike

const myjson = {
"productname0": "Test1",
"price0": "10",
"categories0": "61",
"type0": "Physical",
"availability0": "available",
"weight0": "0.5",
"productname1": "Test2",
"price1": "20",
"categories1": "61",
"type1": "Physical",
"availability1": "available",
"weight1": "0.7",
}

我有一个对象,我想分离对象。所有最后一个数字为 0 的键值都有自己的 json,最后一个数字为 1 的键值有自己的 json。

我想要这个结果

[{
"productname0": "Test1",
"price0": "10",
"categories0": "61",
"type0": "Physical",
"availability0": "available",
"weight0": "0.5",
},
{
"productname1": "Test2",
"price1": "20",
"categories1": "61",
"type1": "Physical",
"availability1": "available",
"weight1": "0.7",
}]

最佳答案

尝试这样

const myjson = {
"productname0": "Test1",
"price0": "10",
"categories0": "61",
"type0": "Physical",
"availability0": "available",
"weight0": "0.5",
"productname1": "Test2",
"price1": "20",
"categories1": "61",
"type1": "Physical",
"availability1": "available",
"weight1": "0.7",
}

var finalArray=[];
Object.keys(myjson).forEach(function(value){
if(value.endsWith("0")){
if(!finalArray[0]){
finalArray[0]={};
}
finalArray[0][value]=myjson[value];
} else if(value.endsWith("1")) {
if(!finalArray[1]){
finalArray[1]={};
}
finalArray[1][value]=myjson[value];
}

});
console.log(finalArray);

更新:

const myjson = {
"productname0": "Test1",
"price0": "10",
"categories0": "61",
"type0": "Physical",
"availability0": "available",
"weight0": "0.5",
"productname1": "Test2",
"price1": "20",
"categories1": "61",
"type1": "Physical",
"availability1": "available",
"weight1": "0.7",
}

var finalArray=[];
Object.keys(myjson).forEach(function(value){

var lastChar = value[value.length -1];

if(!finalArray[lastChar]){
finalArray[lastChar]={};
}
finalArray[lastChar][value]=myjson[value];

});
console.log(finalArray);

关于javascript - 我有一个对象,我想要将对象与给定对象分开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50175450/

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