Reputation: 11055
I have a collection of JavaScript dictionaries that look like
my_dictionary = [
{"first_thing": "1"},
{"second_thing": "2"}
]
, but which need to look like
my_dictionary = [
{key: "first_thing", value: "1"},
{key: "second_thing", value: "2"}
]
. Since there are so many of these dictionaries, I need a way to iterate through them and change all of the dictionaries so that they will have they key
and value
inside.
I have tried iterating through, and tried selecting them using something like my_dictionary[0].key
as well as my_dictionary[0][0]
, which I hoped would work, but I suppose that isn’t the way to do it.
Upvotes: 0
Views: 95
Reputation: 10924
Here's a simple solution using jQuery.each()
var result = [];
var my_dictionary = [{"first_thing": "1"}, {"second_thing":"2"}];
$.each(my_dictionary, function(index, element) {
$.each(element, function(key, value) {
result.push({"key" : key, "value" : value});
});
});
Fiddle here:http://jsfiddle.net/36o170w9/
Upvotes: 0
Reputation: 66404
You can use for..in
No side effects
var dict_in = [{"first_thing": "1"}, {"second_thing": "2"}];
var dict_out = (function (arr) {
var d = [], i, k;
d.length = arr.length;
for (i = 0; i < arr.length; ++i)
for (k in arr[i]) {
d[i] = {'key': k, 'value': arr[i][k]};
break;
}
return d;
}(dict_in));
dict_out; // [{key: "first_thing", value: "1"}, {key: "second_thing", value: "2"}]
Side effects
var dict_in = [{"first_thing": "1"}, {"second_thing": "2"}];
(function (arr) {
var i, k, v;
for (i = 0; i < arr.length; ++i)
for (k in arr[i]) {
v = arr[i][k];
delete arr[i][k];
arr[i].key = k;
arr[i].value = v;
break;
}
return arr;
}(dict_in)); // [{key: "first_thing", value: "1"}, {key: "second_thing", value: "2"}]
Upvotes: -1
Reputation: 10499
Just loop through your dictionary and modify each element in place:
for (var index = 0; index < my_dictionary.length; index++) {
var element = my_dictionary[index],
key, value;
// Grab the initial element
for (var tempKey in element) {
if (element.hasOwnProperty(tempKey)) {
key = tempKey;
value = element[tempKey];
break;
}
}
// Reset the element
element = { "key": key, "value": value };
}
It's not the most elegant solution, but it works.
Upvotes: 0
Reputation: 16726
Since all the transformation is happening in-element, i like using [].map() for this:
[{"first_thing": "1"}, {"second_thing":"2"}].map(function(o){
var o2={};
Object.keys(o).forEach(function(k){o2.key=k; o2.value=o[k];});
return o2;
});
// == [{"key":"first_thing","value":"1"},{"key":"second_thing","value":"2"}]
Upvotes: 2