简体   繁体   English

将字符串数组转换为对象并分配特定的键

[英]Convert array of strings to objects and assign specific key

I'm trying to convert the following array of strings: 我正在尝试转换以下字符串数组:

["one", "two", "three"]

to an array of JSON objects with a specific key of, for instance, number, as follows: 转换为具有特定键(例如,数字)的JSON对象数组,如下所示:

[
    {
        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. 只需使用Array.prototype.map()遍历array中的所有元素并创建一个新元素,同时将它们转换为具有所需结构的object

You can use ES6 to do it with fewer lines of code, but I have also provided a version with ES5: 您可以使用ES6减少代码行,但我还提供了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); 

Then, you can just use JSON.stringify() to get the JSON string representation of it: 然后,您可以只使用JSON.stringify()来获取其JSON string表示形式:

JSON.stringify(arrayOfObjectsES6);

If you want to be able to reuse this functionality using keys other than "number" : 如果您希望能够使用"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')) ); 

Note you can also use a regular for , but I think map() is the cleaner and most concise option here. 请注意,您也可以将常规for ,但我认为map()是此处更简洁,最简洁的选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM