Syafiq apit
Syafiq apit

Reputation: 53

Array of key/value pairs to object

I want to change this

var data = [60, rose, 40, rose1, 20, rose2];

to this

var data: [{
  value: 60,
  name: 'rose'
}, {
  value: 40,
  name: 'rose1'
}, {
  value: 20,
  name: 'rose2'
}];

Upvotes: 4

Views: 85

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386600

Just for the completeness, works even for uneven items:

var data = [60, "rose", 40, "rose1", 20, "rose2", 30],
    object = data.reduce(function (r, a, i, d) {
        if (i % 2) {
            r[d[i - 1]] = a;
        }
        return r;
    }, {});

document.write('<pre>' + JSON.stringify(object, 0, 4) + '</pre>');

Upvotes: 1

CoderPi
CoderPi

Reputation: 13211

You can do it this way:

var data = [60, "rose", 40, "rose1", 20, "rose2"]

var dataObj = []
for (var i = 0; i < data.length; i+=2) {
  dataObj.push({
    value: data[i],
    name: data[i + 1]
  })
}

// Demo Output
document.write(JSON.stringify(dataObj))

Upvotes: 5

Related Questions