将JavaScript数组转换为具有用户定义键的JSON

3

是否有一种干净高效的方法将基本的一维数组转换为:

arrayEx = [1,2,3,4]

将其转换为用户自定义的JSON数组,例如:

jsonArrayEx = [{"exampleKey": 1}, {"exampleKey": 2}, {"exampleKey": 3}, {"exampleKey": 4}]

我曾经看到过使用JSON.Stringify的例子,其中键是基于数组的索引,但从我的示例中没有看到用户定义键的内容。

3个回答

4

当创建一个新对象时,您可以使用 Array#map 和计算属性名.

const arr = [1,2,3,4];
let key = "exampleKey";
const res = arr.map(x => ({[key]: x}));
console.log(res);


2

function mapper(key){ return JSON.stringify(arrayEx.map(a => ({[key]: a})));}

该函数用于将数组中的每个元素转换为一个对象,对象的属性名为参数key的值,属性值为对应的元素值。最终返回一个JSON字符串形式的数组对象。

1

let arr= [1,2,3,4];
let newArr = [];
for(let i of arr){
  newArr.push({"exampleKey" : i});
}
 
  console.log(newArr);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接