我如何将数组与javascript中的ID一起转换为对象数组[关闭]

问题描述 投票:0回答:4

让我们假设我有数组

a = ["hello", "world"]

我如何将其转换为

a = [
    { id : 1, value : "hello" },
    { id : 2, value : "world" } 
]
javascript arrays object ecmascript-6 data-conversion
4个回答
0
投票

这是我的解决方法

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

const b = a.map((item, idx) => ({
  id: idx + 1,
  value: item
}))

console.log(b)

0
投票

使用map方法:

const a = ["hello", "world"];

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

0
投票
  1. 使用map遍历数组。 map返回一个新数组,并应用于每个项目转换
  2. 使用以下规则a转换(str, index) => ({id: index + 1, value: str})的各项。 str将从a中获取每个项目,而index将成为a中的索引。返回具有属性Objectid: index + 1]的新value: str
var a = ["hello", "world"]

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

console.log(b);

0
投票

© www.soinside.com 2019 - 2024. All rights reserved.