0

This is my array:

array = [
 { animal: 'dog', leg: 4, age: 3 },
 { animal: 'chicken', leg: 2, age: 2 },
 { animal: 'egg'},
];

This is my desired array:

desiredArray = [
 { animal: 'dog', leg: 4, age: 3, sum: 7 },
 { animal: 'chicken', leg: 2, age: 2, sum: 4 },
 { animal: 'egg', sum: 0 },
];

I want to add a property to each object in the array which is the sum of the leg and the age. If leg or age is null, it will have a value of 0.

phip
6076 silver badges12 bronze badges
asked Jun 24, 2020 at 3:56

7 Answers 7

2

you can use Array.map function and do the validation directly like this in plain javascript itself

const array = [
 { animal: 'dog', leg: 4, age: 3 },
 { animal: 'chicken', leg: 2, age: 2 },
 { animal: 'egg'},
];
const output = array.map(val => ({...val, sum: (val.leg || 0) + (val.age || 0)}));
console.log(output);

answered Jun 24, 2020 at 4:22
Sign up to request clarification or add additional context in comments.

Comments

2

you can use javascript each loop

var array = [
 { animal: 'dog', leg: 4, age: 3 },
 { animal: 'chicken', leg: 2, age: 2 },
 { animal: 'egg'},
 ];
 $.each(array,function(k,v){
 var total=0;
 if(v.leg)
 total=v.leg;
 if(v.age)
 total=total+v.age 
 v.sum=total
 });
 console.log(array);
answered Jun 24, 2020 at 4:04

Comments

1

array = [
 { animal: 'dog', leg: 4, age: 3 },
 { animal: 'chicken', leg: 2, age: 2 },
 { animal: 'egg'},
];
resultArray = []
for(var item of array) {
 item['sum'] = ('leg' in item?item.leg:0) + ('age' in item?item.age:0)
 resultArray.push(item)
}
console.log(resultArray)

answered Jun 24, 2020 at 4:01

Comments

1

Please Try with one it will work for you and do let me know. I am here looping the array of objects using array.map then adding a new property to the object with the resultant value.

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

const result = array.map((el) => {
 const o: any = Object.assign({}, el);
 o.sum = (el.leg || 0) + (el.age || 0)
 return o;
})
answered Jun 24, 2020 at 4:00

4 Comments

I am using angular and it says property sum does not exist on type
Opps that is due to tslint. Just change const o: any = Object.assign({}, el);. It will work. Check the edited solution, please. I have tested it in angular8 platform.
this returns sum of 0. Expected is 9. { animal: 'egg', leg: 9},
I have updated the answer. It will work in all the conditions.
1

const array = [
 { animal: 'dog', leg: 4, age: 3 },
 { animal: 'chicken', leg: 2, age: 2 },
 { animal: 'egg'},
 { animal: 'special animal', leg: 5},
];
const getDesiredArray = (array) => {
 const desiredArray = array.map( animal => {
 if(animal.leg || animal.age) {
 animal.sum = animal.leg || 0 + animal.age || 0;
 } else {
 animal.sum = 0;
 }
 return animal;
 })
 return desiredArray;
}
console.log(getDesiredArray(array));

answered Jun 24, 2020 at 4:44

Comments

0

If you you have multiple data then you can destructure it and make use of reduce method. Here is a working example:

var array = [ { animal: 'dog', leg: 4, age: 3 }, { animal: 'chicken', leg: 2, age: 2 }, { animal: 'egg'}];
var result = array.map(({animal, ...rest})=>({animal,...rest, sum:Object.values(rest).reduce((s,v)=>s+v,0)}));
console.log(result);

answered Jun 24, 2020 at 5:24

Comments

0

Because you used objects in this code , I think the best approach for this code is JavaScript Object Oriented approach. using this approach your objects will have sum property itself. When you need to see the sum value all you have to do is call it.

I think you in a middle of learning javascript so I post both ES5 and ES6 codes here.

//ES5 solution
var Animal = function (animalName, leg = null, age = null, sum = null) {
 this.animalName = animalName;
 this.leg = leg;
 this.age = age;
 this.sum = sum; //you can set this as this.sum = null if you dont want to assign value when define.
};
Animal.prototype.calcSum = function () {
 if (this.age === null || this.leg === null) { // I used null value , because you mentioned it. In javascript undefined variable value is undefined not null. if you mean 0 or undefined? you can change it.
 this.sum = 0;
 
 } else {
 this.sum = this.leg + this.age;
 }
};
var dog = new Animal("dog", 4, 3);
var chicken = new Animal("chicken", 2, 2);
var egg = new Animal("egg");
var array = [dog, chicken, egg];
array[0].calcSum(); //this will update the value of sum in dog object
array[1].calcSum(); //this will update the value of sum in chicken object
array[2].calcSum(); //this will update the value of sum in egg object
//ES6 solution
class Animal {
 constructor(animalName, leg = null, age = null, sum = null) {
 this.animalName = animalName;
 this.leg = leg;
 this.age = age;
 this.sum = sum;
 }
 calcSum() {
 if (this.age === null || this.leg === null) { // I used null value , because you mentioned it. In javascript undefined variable value is undefined not null. if you mean 0 or undefined? you can change it.
 
 this.sum = 0;
 
 } else {
 this.sum = this.leg + this.age;
 }
 };
}
const dog = new Animal("dog", 4, 3);
const chicken = new Animal("chicken", 2, 2);
const egg = new Animal("egg");
let array = [dog, chicken, egg];
array[0].calcSum(); //this will update the value of sum in dog object
array[1].calcSum(); //this will update the value of sum in chicken object
array[2].calcSum(); //this will update the value of sum in egg object

you can get the sum value using below code line.

console.log(array[1].sum);

answered Jun 24, 2020 at 9:32

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.