0

I have multiple objects that all have the same keys lets say each object has: name and position. The first object will start with position=0. The second object would have position=1. The third object would have position=2 and so on until we get to the 10th object that would have position=9.

I need a way to subtract 1 from every objects position (with only possible values being 0-9 so that 0-1=9)

Looking for a solution that handles all of them mathematically at once, not just re-writing out new values to assign to each key individually.

1 Answer 1

1

Suppose you have an array of JavaScript objects, you could use map:

var newObjs = objects.map(function (object) {
    object.position = (object.position === 9 ? 0 : object.position--);
    return object;
});

A better approach would be:

objects.forEach( function (object) {
    object.position--;
    object.position = object.position < 0 ? 9 : object.position;
}); 
Sign up to request clarification or add additional context in comments.

2 Comments

This works great except for the part: "object.position === 9 ? 0" it doesn't keep all position values between 0 and 9. Anything that has position=0 when this function is ran is going to -1.
Update on above comment, only issue with that part was reversing order of 9 and 0 :)

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.