Related
What is the best way to merge all objects in my array to one and addition all value with the same key?
I tried to achieve this in es6 with the spread operator, but I have no success so far...
const array = [{
on: 1,
off: 1,
alarm: 1,
},{
on: 1,
off: 1,
alarm: 1,
},{
on: 1,
off: 1,
alarm: 1,
}];
const output = [{
on: 3,
off: 3,
alarm: 3,
}];
Another way, using the spread operator as you suggested:
const array = [
{ on: 1, off: 1, alarm: 1 },
{ on: 1, off: 1, alarm: 1 },
{ on: 1, off: 1, alarm: 1 }
];
const output = array.reduce((res, o) => ({
...res,
...Object.fromEntries(
Object.entries(o).map(([k, v]) => [k, v + (res[k] || 0)])
)
}), {});
console.log(output);
Reduce the array, iterate each object entries with Array.forEach(), and assign / add to the respective key on the accumulator (acc):
const array = [{"on":1,"off":1,"alarm":1},{"on":2,"off":2,"alarm":2},{"on":3,"off":3,"alarm":3}];
const result = array.reduce((acc, o) => {
Object.entries(o).
forEach(([k, v]) => acc[k] = (acc[k] ?? 0) + v)
return acc;
}, {});
console.log(result);
OK, here is my two-pennies-worth:
const arr = [{ on: 1, off: 1, alarm: 1},
{on: 1,off: 1,alarm: 1},
{on: 1,off: 1,alarm: 1}];
const res={};
arr.forEach(c=>Object.entries(c).forEach(([k,v])=>res[k]=(res[k] || 0) + v) )
console.log(res)
array.reduce((acc, elem) => {
Object.keys(elem).forEach(key => {
if (acc[key]) {
acc[key] += elem[key];
} else {
acc[key] = elem[key];
}
});
return acc;
}, {})
will return an object {on: 3, off: 3, alarm: 3}
Other solutions appear more elegant, but this was the simplest for me to understand.
const array = [
{ on: 1, off: 1, alarm: 1 },
{ on: 1, off: 1, alarm: 1 },
{ on: 1, off: 1, alarm: 1 }
];
let output = { 'on':0, 'off':0, 'alarm':0 }
array.forEach( (elem,ndx) => { // console.log(ndx, elem)
output.on += elem.on;
output.off += elem.off;
output.alarm += elem.alarm;
});
console.log(JSON.stringify(output,null,2));
I have javascript array object as below. My need is to sum value base on seach id in the array object.
var array = [
{ id: 1, val: 10 },
{ id: 2, val: 25 },
{ id: 3, val: 20 },
{ id: 1, val: 30 },
{ id: 1, val: 25 },
{ id: 2, val: 10 },
{ id: 1, val: 20 }
],
For example sum of value for id 1 is 10 + 30 + 25 + 20 = 85 , It may be something link linq but I'm not sure in javascript. Thanks for all answers.
You can use a combination of filter and reduce to get the result you want:
sumOfId = (id) => array.filter(i => i.id === id).reduce((a, b) => a + b.val, 0);
Usage:
const sumOf1 = sumOfId(1); //85
Reading material:
Array.prototype.filter
Array.prototype.reduce
A way to do it with a traditional for loop
var array = [
{ id: 1, val: 10 },
{ id: 2, val: 25 },
{ id: 3, val: 20 },
{ id: 1, val: 30 },
{ id: 1, val: 25 },
{ id: 2, val: 10 },
{ id: 1, val: 20 }
];
var sums = {};
for (var i = 0; i < array.length; i++) {
var obj = array[i];
sums[obj.id] = sums[obj.id] === undefined ? 0 : sums[obj.id];
sums[obj.id] += parseInt(obj.val);
}
console.log(sums);
running example
You can use reduce() and findIndex()
var array = [
{ id: 1, val: 10 },
{ id: 2, val: 25 },
{ id: 3, val: 20 },
{ id: 1, val: 30 },
{ id: 1, val: 25 },
{ id: 2, val: 10 },
{ id: 1, val: 20 }
];
let res = array.reduce((ac,a) => {
let ind = ac.findIndex(x => x.id === a.id);
ind === -1 ? ac.push(a) : ac[ind].val += a.val;
return ac;
},[])
console.log(res);
JS noob here ... I guess something like this should be here too :-)
let newArray = {}
array.forEach((e) => {
!newArray[e.id] && (newArray[e.id] = 0);
newArray[e.id] += e.val;
});
You can loop on the array and check the ids.
var array = [
{ id: 1, val: 10 },
{ id: 2, val: 25 },
{ id: 3, val: 20 },
{ id: 1, val: 30 },
{ id: 1, val: 25 },
{ id: 2, val: 10 },
{ id: 1, val: 20 }
];
var sum = 0;
var id = 1;
$.each(array, function(index, object){
if (object.id == id) {
sum += object.val;
}
});
console.log(sum);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Using Array#reduce and Map you can get the sum for each id like so. This also uses destructuring to have quicker access to properties.
const data=[{id:1,val:10},{id:2,val:25},{id:3,val:20},{id:1,val:30},{id:1,val:25},{id:2,val:10},{id:1,val:20}];
const res = data.reduce((a,{id,val})=>{
return a.set(id, (a.get(id)||0) + val);
}, new Map())
console.log(res.get(1));
console.log(res.get(2));
If you wanted to output all the sums, then you need to use Array#from
const data=[{id:1,val:10},{id:2,val:25},{id:3,val:20},{id:1,val:30},{id:1,val:25},{id:2,val:10},{id:1,val:20}];
const res = Array.from(
data.reduce((a,{id,val})=>{
return a.set(id, (a.get(id)||0) + val);
}, new Map())
);
console.log(res);
If the format should be similar as to your original structure, you need to add a Array#map afterwards to transform it.
const data=[{id:1,val:10},{id:2,val:25},{id:3,val:20},{id:1,val:30},{id:1,val:25},{id:2,val:10},{id:1,val:20}];
const res = Array.from(
data.reduce((a,{id,val})=>{
return a.set(id, (a.get(id)||0) + val);
}, new Map())
).map(([id,sum])=>({id,sum}));
console.log(res);
You could take GroupBy from linq.js with a summing function.
var array = [{ id: 1, val: 10 }, { id: 2, val: 25 }, { id: 3, val: 20 }, { id: 1, val: 30 }, { id: 1, val: 25 }, { id: 2, val: 10 }, { id: 1, val: 20 }],
result = Enumerable
.From(array)
.GroupBy(null, null, "{ id: $.id, sum: $$.Sum('$.val') }", "$.id")
.ToArray();
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.js"></script>
Here is another option, introducing an Array.prototype.sum helper:
Array.prototype.sum = function (init = 0, fn = obj => obj) {
if (typeof init === 'function') {
fn = init;
init = 0;
}
return this.reduce(
(acc, ...fnArgs) => acc + fn(...fnArgs),
init
);
};
// .sum usage examples
console.log(
// sum simple values
[1, 2, 3].sum(),
// sum simple values with initial value
[1, 2, 3].sum(10),
// sum objects
[{ a: 1 }, { a: 2 }, { a: 3 }].sum(obj => obj.a),
// sum objects with initial value
[{ a: 1 }, { a: 2 }, { a: 3 }].sum(10, obj => obj.a),
// sum custom combinations
[{ amount: 1, price: 2 }, { amount: 3, price: 4 }]
.sum(product => product.amount * product.price)
);
var array = [{ id: 1, val: 10 }, { id: 2, val: 25 }, { id: 3, val: 20 }, { id: 1, val: 30 }, { id: 1, val: 25 }, { id: 2, val: 10 }, { id: 1, val: 20 }];
// solutions
console.log(
array.filter(obj => obj.id === 1).sum(obj => obj.val),
array.filter(({id}) => id === 1).sum(({val}) => val),
array.sum(({id, val}) => id === 1 ? val : 0)
);
references:
Array.prototype.reduce
Array.prototype.filter
Arrow functions used in sum(obj => obj.val)
Object destructing assignment used in ({id}) => id === 1
Rest parameters used in (acc, ...fnArgs) => acc + fn(...fnArgs)
Conditional (ternary) operator used in id === 1 ? val : 0
I have this array of objects:
let foo = [
{
num: 1,
value: 0.5
},
{
num: 1,
value: 1.5
},
{
num: 2,
value: 0.5
},
]
How can I reduce this array to return:
let bar = [
{
num: 1,
value: 2, // 1.5 + 0.5
},
{
num: 2,
value: 0.5
}
]
You can use findIndex to get the object where num is same
let foo = [{
num: 1,
value: 0.5
},
{
num: 1,
value: 1.5
},
{
num: 2,
value: 0.5
},
];
let newData = foo.reduce((acc, curr) => {
let findNumIndex = acc.findIndex(elem => elem.num === curr.num);
if (findNumIndex !== -1) {
acc[findNumIndex].value += curr.value;
} else {
acc.push({...curr})
}
return acc;
}, []);
console.log(newData)
You can use .reduce as follows:
let foo = [
{
num: 1,
value: 0.5
},
{
num: 1,
value: 1.5
},
{
num: 2,
value: 0.5
},
];
var helper = {};
let arr = foo.reduce(function(r, o) {
var key = o.num;
if(!helper[key]) {
helper[key] = Object.assign({}, o);
r.push(helper[key]);
} else {
helper[key].value += o.value;
}
return r;
}, []);
console.log(arr);
Using reduce & Object.assign() like below you can get desired result. Explanation is added as comment in code.
Note I used Object.assign as a.push(Object.assign({}, x)); instead of a.push(x); because with a.push(x); later when we update value while finding existing object it will also update value of foo. Using Object.assign({}, x); this will not happen.
let foo = [{
num: 1,
value: 0.5
},
{
num: 1,
value: 1.5
},
{
num: 2,
value: 0.5
},
];
// use reduce to iterate over array and produce result
var bar = foo.reduce((a, x) => {
// find matching object from a.
let obj = a.filter(y => y.num == x.num)[0];
// if not exists then create new object and add into a
// else add value to obj.value
if (!obj) {
a.push(Object.assign({}, x));
} else {
obj.value += x.value;
}
// return a
return a;
}, []);
console.log(bar);
You could simply sum all the values together in an object, and then afterwards reconstruct the required data
let foo = [
{
num: 1,
value: 0.5
},
{
num: 1,
value: 1.5
},
{
num: 2,
value: 0.5
},
];
// sum all values first
const summedMap = foo.reduce( (agg, cur) => (agg[cur.num] = (agg[cur.num] || 0) + cur.value, agg), {});
// reconstruct afterwards
console.log( Object.entries( summedMap ).map( ([num,value]) => ({ num: parseInt(num), value: value }) ) );
How would I find all values by specific key in a deep nested object?
For example, if I have an object like this:
const myObj = {
id: 1,
children: [
{
id: 2,
children: [
{
id: 3
}
]
},
{
id: 4,
children: [
{
id: 5,
children: [
{
id: 6,
children: [
{
id: 7,
}
]
}
]
}
]
},
]
}
How would I get an array of all values throughout all nests of this obj by the key of id.
Note: children is a consistent name, and id's won't exist outside of a children object.
So from the obj, I would like to produce an array like this:
const idArray = [1, 2, 3, 4, 5, 6, 7]
This is a bit late but for anyone else finding this, here is a clean, generic recursive function:
function findAllByKey(obj, keyToFind) {
return Object.entries(obj)
.reduce((acc, [key, value]) => (key === keyToFind)
? acc.concat(value)
: (typeof value === 'object')
? acc.concat(findAllByKey(value, keyToFind))
: acc
, [])
}
// USAGE
findAllByKey(myObj, 'id')
You could make a recursive function like this:
idArray = []
function func(obj) {
idArray.push(obj.id)
if (!obj.children) {
return
}
obj.children.forEach(child => func(child))
}
Snippet for your sample:
const myObj = {
id: 1,
children: [{
id: 2,
children: [{
id: 3
}]
},
{
id: 4,
children: [{
id: 5,
children: [{
id: 6,
children: [{
id: 7,
}]
}]
}]
},
]
}
idArray = []
function func(obj) {
idArray.push(obj.id)
if (!obj.children) {
return
}
obj.children.forEach(child => func(child))
}
func(myObj)
console.log(idArray)
I found steve's answer to be most suited for my needs in extrapolating this out and creating a general recursive function. That said, I encountered issues when dealing with nulls and undefined values, so I extended the condition to accommodate for this. This approach uses:
Array.reduce() - It uses an accumulator function which appends the value's onto the result array. It also splits each object into it's key:value pair which allows you to take the following steps:
Have you've found the key? If so, add it to the array;
If not, have I found an object with values? If so, the key is possibly within there. Keep digging by calling the function on this object and append the result onto the result array; and
Finally, if this is not an object, return the result array unchanged.
Hope it helps!
const myObj = {
id: 1,
children: [{
id: 2,
children: [{
id: 3
}]
},
{
id: 4,
children: [{
id: 5,
children: [{
id: 6,
children: [{
id: 7,
}]
}]
}]
},
]
}
function findAllByKey(obj, keyToFind) {
return Object.entries(obj)
.reduce((acc, [key, value]) => (key === keyToFind)
? acc.concat(value)
: (typeof value === 'object' && value)
? acc.concat(findAllByKey(value, keyToFind))
: acc
, []) || [];
}
const ids = findAllByKey(myObj, 'id');
console.log(ids)
You can make a generic recursive function that works with any property and any object.
This uses Object.entries(), Object.keys(), Array.reduce(), Array.isArray(), Array.map() and Array.flat().
The stopping condition is when the object passed in is empty:
const myObj = {
id: 1,
anyProp: [{
id: 2,
thing: { a: 1, id: 10 },
children: [{ id: 3 }]
}, {
id: 4,
children: [{
id: 5,
children: [{
id: 6,
children: [{ id: 7 }]
}]
}]
}]
};
const getValues = prop => obj => {
if (!Object.keys(obj).length) { return []; }
return Object.entries(obj).reduce((acc, [key, val]) => {
if (key === prop) {
acc.push(val);
} else {
acc.push(Array.isArray(val) ? val.map(getIds).flat() : getIds(val));
}
return acc.flat();
}, []);
}
const getIds = getValues('id');
console.log(getIds(myObj));
Note: children is a consistent name, and id's wont exist outside
of a children object.
So from the obj, I would like to produce an array like this:
const idArray = [1, 2, 3, 4, 5, 6, 7]
Given that the question does not contain any restrictions on how the output is derived from the input and that the input is consistent, where the value of property "id" is a digit and id property is defined only within "children" property, save for case of the first "id" in the object, the input JavaScript plain object can be converted to a JSON string using JSON.stringify(), RegExp /"id":\d+/g matches the "id" property and one or more digit characters following the property name, which is then mapped to .match() the digit portion of the previous match using Regexp \d+ and convert the array value to a JavaScript number using addition operator +
const myObject = {"id":1,"children":[{"id":2,"children":[{"id":3}]},{"id":4,"children":[{"id":5,"children":[{"id":6,"children":[{"id":7}]}]}]}]};
let res = JSON.stringify(myObject).match(/"id":\d+/g).map(m => +m.match(/\d+/));
console.log(res);
JSON.stringify() replacer function can alternatively be used to .push() the value of every "id" property name within the object to an array
const myObject = {"id":1,"children":[{"id":2,"children":[{"id":3}]},{"id":4,"children":[{"id":5,"children":[{"id":6,"children":[{"id":7}]}]}]}]};
const getPropValues = (o, prop) =>
(res => (JSON.stringify(o, (key, value) =>
(key === prop && res.push(value), value)), res))([]);
let res = getPropValues(myObject, "id");
console.log(res);
Since the property values of the input to be matched are digits, all the JavaScript object can be converted to a string and RegExp \D can be used to replace all characters that are not digits, spread resulting string to array, and .map() digits to JavaScript numbers
let res = [...JSON.stringify(myObj).replace(/\D/g,"")].map(Number)
Using recursion.
const myObj = { id: 1, children: [ { id: 2, children: [ { id: 3 } ] }, { id: 4, children: [ { id: 5, children: [ { id: 6, children: [ { id: 7, } ] } ] } ] }, ]},
loop = (array, key, obj) => {
if (!obj.children) return;
obj.children.forEach(c => {
if (c[key]) array.push(c[key]); // is not present, skip!
loop(array, key, c);
});
},
arr = myObj["id"] ? [myObj["id"]] : [];
loop(arr, "id", myObj);
console.log(arr);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can make a recursive function with Object.entries like so:
const myObj = {
id: 1,
children: [{
id: 2,
children: [{
id: 3
}]
},
{
id: 4,
children: [{
id: 5,
children: [{
id: 6,
children: [{
id: 7,
}]
}]
}]
},
]
};
function findIds(obj) {
const entries = Object.entries(obj);
let result = entries.map(e => {
if (e[0] == "children") {
return e[1].map(child => findIds(child));
} else {
return e[1];
}
});
function flatten(arr, flat = []) {
for (let i = 0, length = arr.length; i < length; i++) {
const value = arr[i];
if (Array.isArray(value)) {
flatten(value, flat);
} else {
flat.push(value);
}
}
return flat;
}
return flatten(result);
}
var ids = findIds(myObj);
console.log(ids);
Flattening function from this answer
ES5 syntax:
var myObj = {
id: 1,
children: [{
id: 2,
children: [{
id: 3
}]
},
{
id: 4,
children: [{
id: 5,
children: [{
id: 6,
children: [{
id: 7,
}]
}]
}]
},
]
};
function findIds(obj) {
const entries = Object.entries(obj);
let result = entries.map(function(e) {
if (e[0] == "children") {
return e[1].map(function(child) {
return findIds(child)
});
} else {
return e[1];
}
});
function flatten(arr, flat = []) {
for (let i = 0, length = arr.length; i < length; i++) {
const value = arr[i];
if (Array.isArray(value)) {
flatten(value, flat);
} else {
flat.push(value);
}
}
return flat;
}
return flatten(result);
}
var ids = findIds(myObj);
console.log(ids);
let str = JSON.stringify(myObj);
let array = str.match(/\d+/g).map(v => v * 1);
console.log(array); // [1, 2, 3, 4, 5, 6, 7]
We use object-scan for a lot of our data processing needs now. It makes the code much more maintainable, but does take a moment to wrap your head around. Here is how you could use it to answer your question
// const objectScan = require('object-scan');
const find = (data, needle) => objectScan([needle], { rtn: 'value' })(data);
const myObj = { id: 1, children: [{ id: 2, children: [ { id: 3 } ] }, { id: 4, children: [ { id: 5, children: [ { id: 6, children: [ { id: 7 } ] } ] } ] }] };
console.log(find(myObj, '**.id'));
// => [ 7, 6, 5, 4, 3, 2, 1 ]
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#13.7.1"></script>
Disclaimer: I'm the author of object-scan
import {flattenDeep} from 'lodash';
/**
* Extracts all values from an object (also nested objects)
* into a single array
*
* #param obj
* #returns
*
* #example
* const test = {
* alpha: 'foo',
* beta: {
* gamma: 'bar',
* lambda: 'baz'
* }
* }
*
* objectFlatten(test) // ['foo', 'bar', 'baz']
*/
export function objectFlatten(obj: {}) {
const result = [];
for (const prop in obj) {
const value = obj[prop];
if (typeof value === 'object') {
result.push(objectFlatten(value));
} else {
result.push(value);
}
}
return flattenDeep(result);
}
Below solution is generic which will return all values by matching nested keys as well e.g for below json object
{
"a":1,
"b":{
"a":{
"a":"red"
}
},
"c":{
"d":2
}
}
to find all values matching key "a" output should be return
[1,{a:"red"},"red"]
const findkey = (obj, key) => {
let arr = [];
if (isPrimitive(obj)) return obj;
for (let [k, val] of Object.entries(obj)) {
if (k === key) arr.push(val);
if (!isPrimitive(val)) arr = [...arr, ...findkey(val, key)];
}
return arr;
};
const isPrimitive = (val) => {
return val !== Object(val);
};
I have the following code and test data:
const getNestedObject = (nestedObj, pathArr) => {
return pathArr.reduce((obj, key) => {
return (obj && obj[key] !== 'undefined') ? obj[key] : undefined, nestedObj;
});
}
const obj =
[
{
a: 1,
c: [
{
d: 1,
e: 'string',
f: [
{
value: 0,
},
{
value: 1,
}
],
},
],
},
{
a: 2,
c: [
{
d: 2,
e: 'string',
f: [
{
value: 3,
},
{
value: 4,
}
],
},
],
},
];
console.log(obj);
const fs = obj.map(o => getNestedObject(o, ['c', 'f']));
console.log(fs);
What I want to do is given the array of objects shown below, I want to get only the property called f from every object in the array. So, basically end result should be array of f values of every object. Since 'f' is an array, I would highly appreciate the end result to be just one array with elements from all 'f' properties, so kind of every of these 'f' to be spread out, so I have one array. My above getNestedObject function does not seem to work, as when the console.log statement below returns the whole object. Any ideas how to do this in JS?
So basically the end result should be:
[{ value: 0 }, { value: 1 }, { value: 3 }, {value: 4 }]
You can combine reduce() with map(). Basically reduce your main array into an flattened array of all the c.f items. This checks for the c property just in case the object doesn't have it:
const obj = [{a: 1,c: [{d: 1,e: 'string',f: [{value: 0,},{value: 1,}],},],},{a: 2,c: [{d: 2,e: 'string',f: [{value: 3,},{value: 4,}],},],},];
let Fs = obj.reduce((arr, item) =>
item.c
? arr.concat(...item.c.map(itemc => itemc.f )) // concat for flattened rather than nested arrays
: arr
, []);
console.log(Fs)
Here's a fast iterative solution that won't overflow the stack, makes no assumptions about target result values being arrays (only spreads if they are) and doesn't hard-code child key names (it'll explore any values that are arrays).
This can also work if the target has children matching the key that you'd like to include in the search (swap else if with if).
const get = (data, target) => {
const result = [];
const stack = [data];
while (stack.length) {
const curr = stack.pop();
for (const o of curr) {
for (const k in o) {
if (k === target) {
if (Array.isArray(o[k])) {
result.push(...o[k]);
}
else {
result.push(o[k]);
}
}
else if (Array.isArray(o[k])) {
stack.push(o[k]);
}
}
}
}
return result;
};
const obj =
[
{
a: 1,
c: [
{
d: 1,
e: 'string',
f: [
{
value: 0,
},
{
value: 1,
}
],
},
],
},
{
a: 2,
c: [
{
d: 2,
e: 'string',
f: [
{
value: 3,
},
{
value: 4,
}
],
},
],
},
];
console.log(get(obj, "f"));
You can recursively traverse any objects and arrays to fetch a given property. This works at any depth and doesn't care about the structure of the objects:
const obj=[{a:1,c:[{d:1,e:"string",f:[{value:0},{value:1}]}]},{a:2,c:[{d:2,e:"string",f:[{value:3},{value:4}]}]}];
//curried function to grab a property by name off some object or array
function grab(prop) {
//naming the inner function means it can be called recursively by name
return function recursiveGrab(target) {
if (Array.isArray(target)) {
const arrayResult = target
.filter(x => typeof x === "object") //remove non-objects (and non-arrays)
.filter(Boolean) //remove null
.map(recursiveGrab); //recursively call for the remaining objects
return flatten(arrayResult); //return a single dimensional array
}
//an object has the property - return it
if (prop in target) {
return target[prop];
}
//object doesn't have the property - check all values
return recursiveGrab(Object.values(target));
}
}
//small helper function. It's separated only to keep the logic for the traversal clear
function flatten(arr) {
return arr.reduce((acc, curr) => acc.concat(curr), [])
}
const grabF = grab('f');
console.log(grabF(obj));
I did not notice that f was always inside c. I have this recursive and dirty looking solution that works with f being inside any of the fields
const objArray = [
{
a: 1,
c: [
{
d: 1,
e: 'string',
f: [
{
value: 0,
},
{
value: 1,
}
],
},
],
d: [
{
d: 1,
e: 'string',
f: [
{
value: 'd',
},
{
value: 'd1',
}
],
},
],
},
{
a: 2,
c: [
{
d: 2,
e: 'string',
f: [
{
value: 3,
},
{
value: 4,
}
],
},
],
e: [
{
d: 1,
e: 'string',
f: [
{
value: 'e',
},
{
value: 'e1',
}
],
},
],
}
]
const getFObject = (obj) => {
let fObj = [];
Object.keys(obj).some(key => {
if (key === 'f') {
fObj = obj[key];
return true;
}
if (Array.isArray(obj[key])) {
obj[key].forEach(nestedObj => {
fObj = fObj.concat(getFObject(nestedObj))
});
}
return false;
});
return fObj;
}
const newArray = objArray.reduce((acc, obj) => {
return acc.concat(getFObject(obj))
}, []);
console.log(newArray)