【问题标题】:How to pass data to a JSON array in nodejs?如何将数据传递给nodejs中的JSON数组?
【发布时间】: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


【解决方案1】:

编辑:

let arr = {
title: "Select a commodity:",
response_type: "option",
description: "",
options:data.map(element => {
  return {
    label: element.Commodity,
    value: {text: element.Commodity}
  }
}) 
}
console.log(arr);

输出

{
response_type: "option"
title: "Select a commodity:"
description: ""
options: Array(5)
0: {label: "Apparel and clothing accessories; knitted or crocheted", value: {…}}
1: {label: "Fish and crustaceans, molluscs and other aquatic invertebrates", value: {…}}
2: {label: "Meat, fish or crustaceans, molluscs or other aquatic invertebrates; preparations thereof", value: {…}}
3: {label: "Natural, cultured pearls; precious, semi-precious …, and articles thereof; imitation jewellery; coin", value: {…}}
4: {label: "Sugars and sugar confectionery", value: {…}}
}

问题是您实际上是在使用“=”运算符,它将值重新分配给您的数组 - arr。 而不是arr = [{... 尝试使用:

var arr = [];
for(let j = 0; j < data.length; j++) {
  arr.push({"title":"Select a commodity:","options":[{"label":data[j]['Commodity'],"value":{"input":{"text":data[j]['Commodity']}}}],"description":"","response_type":"option"});
}

【讨论】:

  • 感谢您的回复,但有没有办法仅在“标签”和“文本”内添加“商品”值? “title”、“description”和“response_type”应保持唯一。
  • @Rohan 他们如何“保持独特”?在 for 循环之前数组是空的。
  • @Rohan 我想这就是你要的?? let arr = { title: "选择商品:", response_type: "option", description: "", options:data.map(element => { return { label: element.Commodity, value: {text: element.Commodity } } }) } console.log(arr);
猜你喜欢
  • 1970-01-01
  • 2021-01-17
  • 2017-12-25
  • 1970-01-01
  • 2020-03-14
  • 1970-01-01
  • 2012-06-06
  • 2011-05-03
  • 2018-04-09
相关资源
最近更新 更多