2

I have an array of objects like this:

[{_colorIndex: 0,name: "ATV Sport"},{_colorIndex: 1,name: "Sport"}]

Id like to loop through that array and replace each _colorIndex value with a value from an array of colors in order. Array:

["#0E5B7E", "#A871A8"]

result:

[{_colorIndex: "#0E5B7E",name: "ATV Sport"},{_colorIndex: "#A871A8",name: "Sport"}]

What would be the best way to do this?

1
  • What would be the best you can show us that you tried so far? Commented Jul 10, 2014 at 19:31

2 Answers 2

2

Assuming that colors array is ALWAYS the same size OR bigger than the object array:

for (var i = 0; i < obj.length; i++) {
    obj[i]._colorIndex = colorArray[i];
}
Sign up to request clarification or add additional context in comments.

7 Comments

What if they are different lengths? the array of colors is fixed but array of objects changes. Sorry, should have specified that.
Why does this assume they are the same size? This should work fine if the colors array is equal in length or larger, since the extra properties won't be looked up, right?
@elclanrs - thats what I was thinking also.
I should've clarified as @elclanrs mentioned, the colors array has to be the same size OR bigger - else an out of bounds index will happen
you may add check e.g. if (typeof colorArray[i] === "string") obj[i]._colorIndex = colorArray[i];
|
1

You can use the map function for this as it is immutable. Unfortunately, it only has IE9+ support.

var data = [{_colorIndex: 0,name: "ATV Sport"},{_colorIndex: 1,name: "Sport"}];
var colors = ["#0E5B7E", "#A871A8"];

function replaceColors(data, colors) {
  return data.map(function(item) {
    var colorIndex = parseInt(item._colorIndex,10);
    if (!isNaN(colorIndex) 
           && (colorIndex > -1)
           && (colorIndex < colors.length)) 
        item._colorIndex = colors[colorIndex]
    return item;
  });
}

var newData = replaceColors(data, colors);

2 Comments

any advantage of using map over a for loop?
Map is immutable meaning it won't change the original array. In most cases, when you change a piece of data it makes it more difficult to maintain. When a bug occurs on that piece of data, you need to walk through the code to find where that piece of data has changed. In this case, you would have to walk through a for loop to find the changes. Using map to produce a new array, you can treat it as a black box and you'll know that you should always get a new array with the specified changes. It's not as performant, but is better for more long term projects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.