0

Let's say I have an array of objects, something like:

{'field1':value1, 'fiedl2':value2, 'field3':value3} ....

{'field1':value4, 'fiedl2':value6, 'field3':value1}

I want each object of the array to be changed, so

for(let item of items){
   //update item so it does not contain the old values but new calculated ones, so
   item.fieldA=item.field1+item.field2;
   item.fieldB=item.field3
}

So in the end, my array should have objects like:

{'fieldA':valueA, 'fieldB':valueB}

I am using node and I am trying to see how I can simply update or replace each object with its updated version with new properties and values

3
  • Youre just missing an delete item.field1 and youre done... Commented Jul 21, 2017 at 18:21
  • 1
    what is item.value1, did you mean item.field1? Where is your array of objects, I just see an object? Commented Jul 21, 2017 at 18:25
  • @James indeed, you are right, I edited. Commented Jul 21, 2017 at 18:31

1 Answer 1

1

It may be worth considering to simply create a new array:

items=items.map(before=>({
 fieldA:before.value1+before.value2,
 fieldB:before.value3
}));

Or pre ES6:

items=items.map(function(before){
 return {
    fieldA:before.value1+before.value2,
     fieldB:before.value3
 };
 }));

Through that, the original items are garbagge collected ( may be easier then deleteing all unused properties), and the syntax is quite nice.

And its may useful to use object destructuring:

items=items.map(
  ({value,value2,unused,...rest})
  =>
  ({result:value+value2,...rest})
);

The upper code deletes unused and replaces value and value2 with their addition stored as result, all the other parameters are copied too.

Sign up to request clarification or add additional context in comments.

5 Comments

@alin youre missing a return { ... } . If the brackets inside the arrow functions are enclosed by (), they arent a block statement anymore but rather an object literal.
Thank you very much I am new to js and missed it. Indeed now it works!
@alin youre welcome ;) i admit that its quite confusing.
I like to use the pre ES6 for functions because I am familiar with java and this makes the move back and forth more easy. Probably I'll have to get into the => one day.
@alin java is focused on readability and js on putting some stuff together very fast , i usually prefer the old function syntax if others need to read it ;)

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.