【问题标题】:how do I convert array into array of object along with id in javascript [closed]如何在javascript中将数组与id一起转换为对象数组[关闭]
【发布时间】:2020-03-25 09:38:09
【问题描述】:

假设我有数组

a = ["hello", "world"]

如何转换成

a = [
    { id : 1, value : "hello" },
    { id : 2, value : "world" } 
]

【问题讨论】:

  • a.map((e, i) => ({ id: (i + 1), value: e }))

标签: javascript arrays object ecmascript-6 data-conversion


【解决方案1】:
  1. 使用map 循环遍历数组。 map 返回一个新数组并应用于每个项目转换
  2. 使用以下规则(str, index) => ({id: index + 1, value: str}) 转换a 的每一项。 str 将从a 中获取每个项目,index 将是它在a 中的索引。返回具有属性id: index + 1value: str 的新Object

var a = ["hello", "world"]

var b = a.map((str, index) => ({id: index + 1, value: str}))

console.log(b);

【讨论】:

    【解决方案2】:

    const arr = ["hello", "world"]; 
    
    const convertArrayToObject = (arr) => {
    	return arr.map((item,index) => {
      		return {id :index+1 ,  value : item}
    	})
    }
    
    console.log(convertArrayToObject(arr));

    这是一个可重用的功能,您可以在您制作的任何东西中使用它。

    【讨论】:

      【解决方案3】:

      这是我的解决方案

      let a = ["hello", "world"] 
      
      const b = a.map((item, idx) => ({
        id: idx + 1,
        value: item
      }))
      
      console.log(b)

      【讨论】:

        【解决方案4】:

        使用ma​​p方法:

        const a = ["hello", "world"];
        
        const b = a.map((item, index) => {
          return { id: index + 1, value: item};
        });
        

        【讨论】:

          猜你喜欢
          • 2018-12-21
          • 1970-01-01
          • 2023-01-02
          • 2018-09-13
          • 1970-01-01
          • 1970-01-01
          • 2019-04-06
          • 2021-12-13
          • 2021-09-16
          相关资源
          最近更新 更多