问题描述:

I know it's a very simple task, but I can't see how to get it. I always get an array with three objects, but all of those objects are identical. So a little help would be truly welcome.

I have an array of objects with one key-value pair and want to convert it into an array of objects with two key-value pairs.

what_i_have = [

{apple: 1.5},

{lemon: 7},

{orange: 4}

]

what_i_want = [

{key: ’apple’, title: ‘apple’},

{key: ‘lemon’, title: ‘lemon’},

{key: ‘orange’, title: ‘orange’}

]

Here I attach my last attempts:

Attempt 1:

var attempt_1 = [];

var key_title_object = {};

for(var i in what_i_have){

key_title_object.key = Object.keys(what_i_have[i])[“0”];

key_title_object.title = Object.keys(what_i_have[i])[“0”];

attempt_1.push(key_title_object)

}

Attempt 2:

var myKeys = [];

for(var i in what_i_have){

var w = Object.keys(what_i_have[i]])["0"]

myKeys.push(w)

}

var attempt_2 = [];

var key_title_object = {};

for (var i in myKeys) {

key_title_object.key = myKeys[i];

key_title_object.title= myKeys[i];

attempt_2.push(key_title_object)

}

Thanks in advance!

相关阅读:
Top