2

Is there a way to add a field to each object of a Javascript array without looping over it?

something like

array.each(function (index, object){
  object[newField] = anotherArray[index];
});
5
  • Just curious about why not loop? Cost too much? Commented Sep 24, 2014 at 8:49
  • are you sure its like function[newField] ? Commented Sep 24, 2014 at 8:49
  • in jquery you can use jQuery.each Commented Sep 24, 2014 at 8:50
  • @osrpt I want to use elements of functional programming where possible and was just wondering about the possibilities to do this in javascript. Commented Sep 24, 2014 at 8:51
  • I would say array.forEach (map, sum etc) is the functional programming alternative to classic looping Commented Sep 24, 2014 at 8:57

1 Answer 1

2

You might be interested in the differences between an Object ({}) and an Array ([]).

Currently, a cached length loop offers the best performance for an Array.

But Array also offers a method forEach: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

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.