Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array having multiple inner objects,extract an deeper inner objects as an array

What I had

{
     "1zkhj45kjb3h3jj27777fjd": {"-L7hgtdyYUYY56":{ email: "[email protected]",name:"abc"   } },
     "1zkhj45kjb3h898fj7fjddk": {"-L7hgtdyYUYY56":{ email: "[email protected]",name:"dumy" } } 
}

What I've done

const snapshot = snap.val()
const items = Object.values(snapshot)

now items looks like

[
    {"-L7hgtdyYUYY56":{ email: "[email protected]",name:"abc"   } },
    {"-L7hgtdyYUYY56":{ email: "[email protected]",name:"dumy" } } 
]

But I want

[
    { email: "[email protected]",name:"abc"   } ,
    { email: "[email protected]",name:"dumy" } 
]

I have tried all other stretegies like Object.keys, Object.enteries. if I again call object.values it gives same result.

How to do it javascript ? I'm newbie to react native and javascript.

Thank you!

like image 327
Muhammad Ashfaq Avatar asked Jan 19 '26 22:01

Muhammad Ashfaq


2 Answers

Use Array.flatMap() with Object.values() to get an array of the inner objects:

const items = {
     "1zkhj45kjb3h3jj27777fjd": {"-L7hgtdyYUYY56":{ email: "[email protected]",name:"abc"   } },
     "1zkhj45kjb3h898fj7fjddk": {"-L7hgtdyYUYY56":{ email: "[email protected]",name:"dumy" } } 
}

const result = Object.values(items).flatMap(Object.values)
  
console.log(result)

If Array.flatMap() is not supported, use Array.map() instead. However, the result would be an array of arrays, so you'll need to flatten it. You can flatten it by spreading the array of arrays into Array.concat():

const items = {
     "1zkhj45kjb3h3jj27777fjd": {"-L7hgtdyYUYY56":{ email: "[email protected]",name:"abc"   } },
     "1zkhj45kjb3h898fj7fjddk": {"-L7hgtdyYUYY56":{ email: "[email protected]",name:"dumy" } } 
}

const result = [].concat(...Object.values(items).map(Object.values))
  
console.log(result)
like image 64
Ori Drori Avatar answered Jan 22 '26 11:01

Ori Drori


Use Object.values() twice with map() and flat():

const data = {
 "1zkhj45kjb3h3jj27777fjd": {"-L7hgtdyYUYY56":{ email: "[email protected]",name:"abc"   } },
 "1zkhj45kjb3h898fj7fjddk": {"-L7hgtdyYUYY56":{ email: "[email protected]",name:"dumy" } } 
};

const result = Object.values(data).map(Object.values).flat();

console.log(result);
like image 37
jo_va Avatar answered Jan 22 '26 10:01

jo_va



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!