Essentially, I would like to make:
var current = [
[4, 'socks'],
[2, 'pants'],
[1, 'shoes'],
[5, 'hats']
];
Into this:
var current = {
socks: 4,
pants: 2,
shoes: 1,
hats: 5
};
Essentially, I would like to make:
var current = [
[4, 'socks'],
[2, 'pants'],
[1, 'shoes'],
[5, 'hats']
];
Into this:
var current = {
socks: 4,
pants: 2,
shoes: 1,
hats: 5
};
If you want to iterate through a collection and return a single object then reduce()
is your tool:
var current = [
[4, 'socks'],
[2, 'pants'],
[1, 'shoes'],
[5, 'hats']];
current.reduce(
function(m,c) {
m[c[1]] = c[0];
return m;
}, {})
// Object {socks: 4, pants: 2, shoes: 1, hats: 5}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
You can loop through the arrays in the array and add them as properties in the object:
var result = {};
for (var i = 0; i < current.length; i++) {
result[current[i][1]] = current[i][0];
}
Demo:
var current = [
[4, 'socks'],
[2, 'pants'],
[1, 'shoes'],
[5, 'hats']];
var result = {};
for (var i = 0; i < current.length; i++) {
result[current[i][1]] = current[i][0];
}
// show result in snippet
document.write(JSON.stringify(result));
With [].forEach.call()
:
var current = [
[4, 'socks'],
[2, 'pants'],
[1, 'shoes'],
[5, 'hats']
];
var res = {};
[].forEach.call(current, function(el) {
res[el[1]] = el[0];
});
console.log(res);
var html = document.getElementById("result");
result.innerHTML = JSON.stringify(res);
<div id="result"></div>