【发布时间】:2021-06-09 17:06:54
【问题描述】:
我想将数据从一个 JSON 数组传递到另一个。我的第一个 json 数组如下:
var data = [{"Commodity":"Apparel and clothing accessories; knitted or crocheted"},{"Commodity":"Fish and crustaceans, molluscs and other aquatic invertebrates"},{"Commodity":"Meat, fish or crustaceans, molluscs or other aquatic invertebrates; preparations thereof"},{"Commodity":"Natural, cultured pearls; precious, semi-precious stones; precious metals, metals clad with precious metal, and articles thereof; imitation jewellery; coin"},{"Commodity":"Sugars and sugar confectionery"}];
我想将每个“商品”值传递给我的第二个 JSON 数组。我尝试使用 for 循环:
var arr = [];
for(let j = 0; j < data.length; j++) {
arr = [{"title":"Select a commodity:","options":[{"label":data[j]['Commodity'],"value":{"input":{"text":data[j]['Commodity']}}}],"description":"","response_type":"option"}];
}
我需要将每个“商品”值填充到“标签”和“文本”属性中。但是在输出时,arr 中只显示了最后一个“商品”-“糖和糖果”。
任何想法都会有所帮助。谢谢。
更新:
这是输出的样子,但“选择商品”应该只打印一次。这是来自 ibm watson assistant 的响应类型选项。
【问题讨论】:
-
这些是数组,不是 JSON 数组。 JSON 是一种文本格式。
-
而不是
arr = [{...}],它每次都会覆盖数组,只需使用arr.push({...}) -
@AntonMitsev 我做了
-
由于您得到的代码完全符合您的要求,但显然您正在寻找不同的东西,请在您的问题中添加所需输出的示例。
-
@ChrisG 我更新了问题中的输出。
标签: javascript node.js arrays json for-loop