将字符串数组转换为对象并分配特定的键 [英] Convert array of strings to objects and assign specific key
问题描述
我正在尝试转换以下字符串数组:
I'm trying to convert the following array of strings:
["one", "two", "three"]
到具有特定键(例如,数字)的JSON对象数组,如下所示:
to an array of JSON objects with a specific key of, for instance, number, as follows:
[
{
number: 'one'
},
{
number: 'two'
},
{
number: 'three'
}
]
推荐答案
Just use Array.prototype.map() to iterate over all the elements in the array
and create a new one while converting them to an object
with the structure you need.
您可以使用 ES6 来使用较少的代码行来完成此操作,但是我还提供了一个ES5:
You can use ES6 to do it with fewer lines of code, but I have also provided a version with ES5:
// ES6:
const arrayOfObjectsES6 = ["one", "two", "three"].map(number => ({ number }));
console.log(arrayOfObjectsES6);
// ES5:
var listOfObjectsES5 = ["one", "two", "three"].map(function(value) {
return { number: value };
});
console.log(listOfObjectsES5);
然后,您只需使用 JSON.stringify()
来获取其JSON string
表示形式:
Then, you can just use JSON.stringify()
to get the JSON string
representation of it:
JSON.stringify(arrayOfObjectsES6);
如果您希望能够使用数字"
以外的其他键来重复使用此功能:
If you want to be able to reuse this functionality using keys other than "number"
:
function getArrayOfObjectsES6(values, key) {
return values.map(value => ({ [key]: value }))
}
console.log( JSON.stringify(getArrayOfObjectsES6(["one", "two", "three"], 'ES6')) );
function getArrayOfObjectsES5(values, key) {
return values.map(function(value) {
var obj = {};
obj[key] = value;
return obj;
});
}
console.log( JSON.stringify(getArrayOfObjectsES6(["one", "two", "three"], 'ES5')) );
请注意,您也可以将常规用于
,但是我认为 map()
是这里更简洁,最简洁的选择.
Note you can also use a regular for
, but I think map()
is the cleaner and most concise option here.
这篇关于将字符串数组转换为对象并分配特定的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!