如何从javascript或jquery中的数组中添加键到对象 [英] how to add key to object from array in javascript or jquery
问题描述
如何将键值添加到javascript对象,
我有一个像这样的数组:
var a = [20, 21, 22];
How to add a key value to javascript object,
i have an array like this :
var a = [20, 21, 22];
,我尝试使用以下代码将其转换为javascript对象:
var id = Object.assign({}, a);
and i tried to convert it into a javascript object using this code :
var id = Object.assign({}, a);
结果是:{0 : 20, 1 : 21, 2 : 22}
但是,如何像下面的对象一样更改结果? :
but, how to change the result like an object below ? :
0 : {id : 20}, 1 : {id : 21}, 2 : {id : 22}
任何帮助将不胜感激
推荐答案
根据您的评论该对象的格式应该是这样的:0:{id:20},1:{id:21},2 :{id:22},这看起来像是
Based on your comment "the format of the object supposed to be like this: 0 : {id : 20}, 1 : {id : 21}, 2 : {id : 22}", this looks like a job for .map()
:
var input = [ 20, 21, 22 ];
var output = input.map( function( value ) {
return { id: value };
});
console.log( output );
或者,在现代JavaScript中,使用箭头功能:
Or, in modern JavaScript using an arrow function:
var input = [ 20, 21, 22 ];
var output = input.map( value => ({ id: value }) );
console.log( output );
这篇关于如何从javascript或jquery中的数组中添加键到对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!