【发布时间】:2021-12-14 06:54:48
【问题描述】:
尝试创建一个新对象,然后从 JSON 文件中的嵌套值连接所有对象。
JSON 数据比较大,所以拿了个样本,叫它 var items
我遇到的问题是嵌套数据没有更新新对象。
var items = [
{
"id": 11,
"title": "Fruit Test",
"releaseDateTime": "2021-10-21T10:50:00+09:30",
"mainContent": "Fruit order for 1 person",
"storeNames": [
"Store 1"
],
"items": [
{
"itemName": "Melon",
"otherName": "Watermelon"
},
{
"itemName": "Apple",
"otherName": "Red apple"
}
]
},
{
"id": 12,
"title": "Canned Test",
"releaseDateTime": "2021-10-21T10:50:00+09:30",
"mainContent": "Canned order for 2 people",
"storeNames": [
"Store 1"
],
"items": [
{
"itemName": "Tomatoes",
"otherName": "Diced tomato"
}
]
},
{
"id": 13,
"title": "Dairy Test",
"releaseDateTime": "2021-10-21T10:50:00+09:30",
"mainContent": "Dairy Order for 2 people",
"storeNames": [
"Store 1"
],
"items": []
}
]
;
var copyItems = [];
for (let i = 0; i < items.length; i++) {
items[i].allItems = items[i].items;
copyItems.push(items[i])
}
console.log(copyItems);
var copyItems = copyItems.map(function(elem){
return elem.allItems;
}).join(",");
console.log(`These are the final items ${copyItems}`);
我能够创建新对象,并将嵌套数组添加到其中。但是我试图让 allItems 对象显示如下信息:
[
{
"id": 11,
"allItems": "Melon, Apple",
"title": "Fruit Test",
"releaseDateTime": "2021-10-21T10:50:00+09:30",
"mainContent": "Fruit order for 1 person",
"storeNames": [
"Store 1"
],
"items": [
{
"itemName": "Melon",
"otherName": "Watermelon"
},
{
"itemName": "Apple",
"otherName": "Red apple"
}
]
},
{
"id": 12,
"allItems": "Tomatoes",
"title": "Canned Test",
"releaseDateTime": "2021-10-21T10:50:00+09:30",
"mainContent": "Canned order for 2 people",
"storeNames": [
"Store 1"
],
"items": [
{
"itemName": "Tomatoes",
"otherName": "Diced tomato"
}
]
},
{
"id": 13,
"allItems": "",
"title": "Dairy Test",
"releaseDateTime": "2021-10-21T10:50:00+09:30",
"mainContent": "Dairy Order for 2 people",
"storeNames": [
"Store 1"
],
"items": []
}
]
这是我的 JSFiddle:https://jsfiddle.net/buogdvx9/6/
Javascript 仍然是我正在学习和使用的一门语言,但有些东西仍然让我很着迷。
谢谢。
【问题讨论】:
-
请澄清一下,您希望得到哪种输出。一些例子会很好。
-
不清楚预期的输出是什么。您的代码似乎针对 one 字符串输出,列出所有项目名称。但是随后您为我们提供了一个具有附加属性的对象数组。不清楚你想要哪两个。
标签: javascript arrays json object