是否有一种干净高效的方法将基本的一维数组转换为:
arrayEx = [1,2,3,4]
将其转换为用户自定义的JSON数组,例如:
jsonArrayEx = [{"exampleKey": 1}, {"exampleKey": 2}, {"exampleKey": 3}, {"exampleKey": 4}]
我曾经看到过使用JSON.Stringify的例子,其中键是基于数组的索引,但从我的示例中没有看到用户定义键的内容。
是否有一种干净高效的方法将基本的一维数组转换为:
arrayEx = [1,2,3,4]
将其转换为用户自定义的JSON数组,例如:
jsonArrayEx = [{"exampleKey": 1}, {"exampleKey": 2}, {"exampleKey": 3}, {"exampleKey": 4}]
我曾经看到过使用JSON.Stringify的例子,其中键是基于数组的索引,但从我的示例中没有看到用户定义键的内容。
当创建一个新对象时,您可以使用 Array#map
和计算属性名.
const arr = [1,2,3,4];
let key = "exampleKey";
const res = arr.map(x => ({[key]: x}));
console.log(res);
function mapper(key){ return JSON.stringify(arrayEx.map(a => ({[key]: a})));}
let arr= [1,2,3,4];
let newArr = [];
for(let i of arr){
newArr.push({"exampleKey" : i});
}
console.log(newArr);