DarkCode999
DarkCode999

Reputation: 182

how to add key to object from array in javascript or jquery

How to add a key value to javascript object, i have an array like this : var a = [20, 21, 22];

and i tried to convert it into a javascript object using this code : var id = Object.assign({}, a);

the result is : {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}

any help will be appreciated

Upvotes: 2

Views: 853

Answers (4)

Michael Geary
Michael Geary

Reputation: 28850

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 );

Or, in modern JavaScript using an arrow function:

var input = [ 20, 21, 22 ];

var output = input.map( value => ({ id: value }) );

console.log( output );

Upvotes: 3

Aydin4ik
Aydin4ik

Reputation: 1935

You can't and shouldn't have an object like {id : 20, id: 21, id:22}. Each key in the object should be unique, otherwise it beats the purpose of being a 'key'.

If you, hypothetically, had an object like

var a = {id : 20, id: 21, id:22};

,then how are you planning to access those elements? What will a.id return and how will it help you?

If you want to get 0 : {id : 20}, 1 : {id : 21}, 2 : {id : 22}, you could do this this way:

let a = [20, 21, 22];
let obj = Array();
for(let i of a) {
  obj.push({id: i});
}

Upvotes: 2

marvel308
marvel308

Reputation: 10458

{id : 20, id: 21, id:22} is equivalent to just 1 key/value pair. their is no way to have {id : 20, id: 21, id:22} as an object and keep values as 20, 21, 22

You can try making it into an array like

{id : [20, 21, 22]}

or

[{id:20}, {id:21}, {id:22}]

var a = [20, 21, 22];
var result = [];

for(let i=0; i<a.length; i++){
    result.push({id: a[i]});
}

//console.log(result)
var id = Object.assign({}, result);
console.log(id);

Upvotes: 0

Altaf Khokhar
Altaf Khokhar

Reputation: 306

Create object like: var collections = [], a = [20, 21, 22];

Iterate array a([20, 21, 22]), and add individual item in collections like below which is array.

for (i = 0; i < a.length; i++) {
    collections.push({id: a[i]});
}

Cheers...

Upvotes: 0

Related Questions