gpt4 book ai didi

javascript - 在将两者相加时如何防止对象转换为字符串?

转载 作者:行者123 更新时间:2023-11-28 17:08:55 26 4
gpt4 key购买 nike

我正在尝试编写一个逻辑来修改包含列表的数组 的物体。例如:

    [
{
"S.N.": "1",
"ITEM": "CIGARETTES",
" QUANTITY SOLD ": " 3,603,221 ",
"UNIT OF MEASURE": "CARTONS"
},
{
"S.N.": "2",
"ITEM": "LIQUOR",
" QUANTITY SOLD ": " 5,680,586 ",
"UNIT OF MEASURE": "BOTTLES"
},
{
"S.N.": "3",
"ITEM": "BEER",
" QUANTITY SOLD ": " 7,581,446 ",
"UNIT OF MEASURE": "CANS"
}]

这样我会得到如下的最终结果:

    "CIGARETTES": {
"S.N.": "1",
"ITEM": "CIGARETTES",
"QUANTITY": " 3,603,221 ",
"UNIT": "CARTONS"
},
"LIQUOR": {
"S.N.": "2",
"ITEM": "LIQUOR",
"QUANTITY": " 5,680,586 ",
"UNIT": "BOTTLES"
},
"BEER": {
"S.N.": "3",
"ITEM": "BEER",
"QUANTITY": "7,581,446 ",
"UNIT": "CANS"
}

我希望 ITEM 名称显示在上面给出的对象之前。我的逻辑如下:

    var callMe = function(){
var newJson = json.map(function(item){
var newItem = JSON.stringify(JSON.parse(item));
newItem = item.ITEM + ':' + {item};
return console.log(newItem)
})
}

当我安慰它时,我收到以下信息:

 CIGARETTES:[object Object]
LIQUOR:[object Object]
BEER:[object Object]
GOLD:[object Object]
WATCHES:[object Object]

请告诉我如何阻止对象转换为字符串。

最佳答案

对于什么是 JSON(Javascript 对象表示法)似乎存在误解。它只是正在发送的数据的格式。

您正在使用的只是一个数组/对象。

您永远不应该修改字符串化对象来添加数据。使用对象本身,然后将其字符串化。

const data=[{"S.N.":"1","ITEM":"CIGARETTES"," QUANTITY SOLD ":" 3,603,221 ","UNIT OF MEASURE":"CARTONS"},{"S.N.":"2","ITEM":"LIQUOR"," QUANTITY SOLD ":" 5,680,586 ","UNIT OF MEASURE":"BOTTLES"},{"S.N.":"3","ITEM":"BEER"," QUANTITY SOLD ":" 7,581,446 ","UNIT OF MEASURE":"CANS"}]

const res = data.reduce((a,c)=>{
a[c.ITEM] = c;
return a;
}, {});

console.log(res);

//then JSON.stringify res

非缩减版本:

const data=[{"S.N.":"1","ITEM":"CIGARETTES"," QUANTITY SOLD ":" 3,603,221 ","UNIT OF MEASURE":"CARTONS"},{"S.N.":"2","ITEM":"LIQUOR"," QUANTITY SOLD ":" 5,680,586 ","UNIT OF MEASURE":"BOTTLES"},{"S.N.":"3","ITEM":"BEER"," QUANTITY SOLD ":" 7,581,446 ","UNIT OF MEASURE":"CANS"}]

const res = {};
for(let i = 0; i < data.length; i++){
res[data[i].ITEM] = data[i];
}

console.log(res);

//then JSON.stringify res

关于javascript - 在将两者相加时如何防止对象转换为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55024580/

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