Benn
Benn

Reputation: 5023

Need help building a javascript array from given object values.

This is an object that I have.

var MyObject  =  {
    'stop1-start': "0", 
    'stop1-color': "#0074a2", 
    'stop2-start': "32", 
    'stop2-color': "#ff6600"
};

this is an array that I need.

var newArray =[
    {
        'stop-start': "0",
        'stop-color': "#0074a2",
    },
    {
        'stop-start': "32",
        'stop-color': "#ff6600",
    }
];

I tried for loops, jquery each but just cant wrap my head around it.

Any help is appreciated.

Upvotes: -1

Views: 54

Answers (3)

Rick Hitchcock
Rick Hitchcock

Reputation: 35670

Object keys are not guaranteed to be in order, so you'll need to find the array's index within the key itself:

var MyObject  =  {
  'stop1-start': "0", 
  'stop1-color': "#0074a2", 
  'stop2-start': "32", 
  'stop2-color': "#ff6600"
};

var newArray= [];

Object.keys(MyObject).sort().forEach(function(key) {
  var num= key.match(/(\d+)/)[0] - 1;
  newArray[num] = newArray[num] || {};
  newArray[num][key.replace(num+1,'')]= MyObject[key];
});

document.body.innerHTML= JSON.stringify(newArray);

Upvotes: 1

ssube
ssube

Reputation: 48247

You should figure out which numbers are present first, for safety's sake, then turn each pair into a record. Like so:

var MyObject = {
  'stop1-start': "0",
  'stop1-color': "#0074a2",
  'stop2-start': "32",
  'stop2-color': "#ff6600"
};

function createArray(data) {
  // Figure out which numbers are present
  var numbers = Object.keys(data).map(function(key) {
    return parseInt(key.match(/stop(\d+)/)[1], 10);
  });

  // Filter out duplicates
  numbers = numbers.filter(function (num, idx, arr) {
    // Only take the first instance of each value
    return arr.indexOf(num) === idx; 
  }).sort();

  // For each number, create a record
  var records = numbers.map(function(num) {
    var start = 'stop' + num + '-start';
    var color = 'stop' + num + '-color';
    return {
      start: data[start],
      color: data[color]
    };
  });
  
  return records;
}

document.getElementById('r').textContent = JSON.stringify(createArray(MyObject));
<pre id=r></pre>

If you want to get all clever and functional, you can turn the whole algorithm into a single chain:

function createArray(data) {
  // Figure out which numbers are present
  return Object.keys(data).map(function(key) {
    return parseInt(key.match(/stop(\d+)/)[1], 10);
  }).filter(function (num, idx, arr) {
    // Only take the first instance of each value
    return arr.indexOf(num) === idx; 
  }).sort().map(function(num) {
    var start = 'stop' + num + '-start';
    var color = 'stop' + num + '-color';
    return {
      start: data[start],
      color: data[color]
    };
  });
}

If you have access to ES6, you can use that for some shorthand:

function createArray(data) {
  return Object.keys(data)
    .map(key =>  parseInt(key.match(/stop(\d+)/)[1], 10))
    .filter((num, idx, arr) => arr.indexOf(num) === idx)
    .sort()
    .map(num => {
      return {
        start: data[`stop${num}-start`],
        color: data[`stop${num}-color`]
      };
    });
}

Upvotes: 3

Try:

var newArray = [], current = {}, i = 0;

for(var key in MyObject){
    current[i % 2 ? "stop-color" : "stop-start"] = MyObject[key];
    i++ % 2 && (newArray.push(current), current = {})
}

Demo

Upvotes: 1

Related Questions