0

I'm currently struggling to add some numbers to an object like we do for arrays using push().

I have an array that looks like this:

$scope.order = [
  {sequenceNumber:1},
  {sequenceNumber:2},
  {sequenceNumber:3}  
];

And i'm using a forEach method to add the numbers to an object "newOrder"

var newOrder = {};

angular.forEach($scope.order, function(orderValue) {
  newOrder = orderValue.sequenceNumber;
});

However...this doesnt return the result that i want

I want "newOrder" to look like this:

var newOrder = {
  1: 1,
  2: 2,
  3: 3
};

Value = position of the array

Key = sequenceNumber

1 Answer 1

1

You could use Array.prototype.reduce in this case, like so:

var newOrder = $scope.order.reduce(function(acc, item, index) {
  acc[item.sequenceNumber] = index;
  return acc;
}, {});

Or shorter equivalent:

var newOrder = $scope.order.reduce((acc, {sequenceNumber}, index) => {
  acc[sequenceNumber] = index;
  return acc;
}, {});
Sign up to request clarification or add additional context in comments.

Comments

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.