[英]Convert array to object wrapped with square brackets [ ]
I'm already looking in Convert Array to Object but it looks different. 我已经在将数组转换为对象中寻找了,但是看起来却有所不同。 I mean, how i can convert array to object with the square brackets format at the start and end of the object?
我的意思是,我如何才能在对象的开头和结尾将方括号格式的数组转换为对象?
Array : 数组:
['a','b','c']
to : 至 :
[
{
0: 'a',
1: 'b',
2: 'c'
}
]
Anyone can help? 有人可以帮忙吗?
Use the toObject
function from the answer you mentioned and wrap the result in an array: 使用您提到的答案中的
toObject
函数并将结果包装在数组中:
[toObject(['a', 'b', 'c'])]
Or if you are using ES6+, you can do: 或者,如果您使用的是ES6 +,则可以执行以下操作:
[{...['a', 'b', 'c']}]
There is various way to achieve this, try with Array.forEach method , 有多种方法可以实现,请尝试使用Array.forEach方法,
var orgArrayData = ['a','b','c','d'];
var convertedFormatData = [];
var tempObj = {};
convertArrayElemToObject(orgArrayData);
function convertArrayElemToObject(orgArrayData){
orgArrayData.forEach((element,index)=>{
tempObj[index] = element;
});
};
convertedFormatData.push(tempObj);
console.log(convertedFormatData);
o/p - o / p-
[
0: {0: "a", 1: "b", 2: "c", 3: "d"}
]
i hope, it will help to you. 希望对您有帮助。
use Object.assign 使用Object.assign
const a = ['a', 'b', 'c']; const newObject = Object.assign({}, a); console.log(newObject);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.