var arr = [{req: [{type: 'high', val: 1},{type: 'low', val: 2}], other: [{random: 123}]}, {req: [{type: 'cool', val: 1},{type: 'med', val: 3}], other: [{random: 456}]}]
how write function using array functions to get value of val
which is 3 from above array of objects from inside array of objects where type
is med
expected result
var result = 3;
I tried to use reduce function of array
let getRequirementArray = (req, vol) =>
req.reduce((currentVal, obj) => {
return obj.type === vol ? obj.val + currentVal : currentVal;
}, 0);
let getFinalOutput = (arr, vol) =>
arr.reduce((currentVal, obj) => {
let { req } = obj;
let val= getRequirementArray(req, vol);
return val + currentVal;
}, 0);
var result = getFinalOutput(arr, 'med');
But I am expecting a little smaller function
You can aggregate the array into a single array of objects and then find the object with type
equal to med
var arr = [{req: [{type: 'high', val: 1},{type: 'low', val: 2}], other: [{random: 123}]}, {req: [{type: 'cool', val: 1},{type: 'med', val: 3}], other: [{random: 456}]}] var mix = [].concat(...arr.map(t => t.req)); var obj = mix.find(x => x.type === 'med'); console.log(obj.val);
You can use every function of Arrays and return false when you got the first value
var value,arr = [{req: [{type: 'high', val: 1},{type: 'low', val: 2}], other: [{random: 123}]}, {req: [{type: 'cool', val: 1},{type: 'med', val: 3}], other: [{random: 456}]}] arr.every(outerObject => {let desObj = outerObject.req.find(obj => obj.type == "med");if (desObj){value=desObj.val;return false;}return true; }); console.log(value);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.