【问题标题】:How could I create object from array? [closed]如何从数组创建对象? [关闭]
【发布时间】:2020-10-05 16:36:51
【问题描述】:

我想使用循环从包含许多元素的数组中创建 json 对象

我怎样才能从这个数组中返回这个对象?

我的数组:

[
"text 1",
"text 2",
"text 3"
]

我想归还的对象:

return [
  {
    json: {
      message: "text 1"
    } 
  },
  {
    json: {
      message: "text 2"
    }
  },
  {
    json: {
      message: "text 3"
    }
  }
]

【问题讨论】:

  • 我看不到 json ...
  • 考虑使用Array.map

标签: javascript arrays json object


【解决方案1】:

您可以使用Array.map 完成此操作

const input = [
  "text 1",
  "text 2",
  "text 3"
];

const output = input.map((item) => ({
  json: {
    message: item
  }
}));

console.log(output);

【讨论】:

    【解决方案2】:
    let arr = [ "text 1", "text 2", "text 3" ];
    let response = [];
    
    for (let i = 0; i < arr.length; i++) {
       response.push({
        json: {
          message: arr[i];
        } 
      });
    }
    
    return response;
    

    虽然上述代码对您有所帮助,但写下您为解决问题所做的尝试以及在此过程中是否遇到任何挑战通常是一个好习惯

    【讨论】:

      【解决方案3】:

      您可以在推送到对象时遍历数组:

      const originalArray = [
      "text 1",
      "text 2",
      "text 3"
      ]
      
      let newArray = []
      
      for (const arrayItem of originalArray) {
          newArray.push({json: {message: arrayItem}})
      }
      
      

      【讨论】:

        【解决方案4】:

        这将是使用地图的一个很好的用例。 Map 允许您遍历由传递给它的函数的结果填充的数组。在这种情况下,该函数将创建一个带有字段“json”的新对象,其中包含另一个带有字段“message”的对象。

        let arr  =[
        "text 1",
        "text 2",
        "text 3"
        ];
        let jsonArr = arr.map(message=>{
            return ({json:{message}});
        });
        

        【讨论】:

          猜你喜欢
          • 2019-04-08
          • 1970-01-01
          • 2018-08-20
          • 2022-12-15
          • 1970-01-01
          • 1970-01-01
          • 2019-09-23
          • 1970-01-01
          • 2018-02-01
          相关资源
          最近更新 更多