Muhammad Ashfaq
Muhammad Ashfaq

Reputation: 2531

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!

Upvotes: 2

Views: 73

Answers (3)

jo_va
jo_va

Reputation: 13983

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);

Upvotes: 3

Ori Drori
Ori Drori

Reputation: 192857

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)

Upvotes: 4

Barmar
Barmar

Reputation: 782344

Use Object.values() to get the nested objects as an array, then use .map() to get the value of the -L7hgtdyYUYY56 of each of them.

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

var result = Object.values(snapshot).map(e => e["-L7hgtdyYUYY56"]);
console.log(result);

This assumes that the nested objects just have one property and they're all the same property name, as in your example. If it's more dynamic, the other answers that flatten the objects are more appropriate.

Upvotes: 1

Related Questions