0

I would like to transform an object in an array, removing the objects that have no values. So I would like to create this new array of objects.

Object I am receving:

{
    "61e048080589f874231c1a85": [
        {
            "xAxesListings": "61e048080589f874231c1a85",
            "xAxesProducts": 0
        },
        {
            "xAxesListings": "61e048080589f874231c1a85",
            "xAxesProducts": 1
        },
        {
            "xAxesListings": "61e048080589f874231c1a85",
            "xAxesProducts": 2
        }
    ],

    "61f2f65190c83cffb800bda3": [
        0,
        0
    ],

    "61f7000ea4f1662e206d5c0f": [
        {
            "xAxesListings": "61f7000ea4f1662e206d5c0f",
            "xAxesProducts": 0
        }
    ]
}


Expected output:
[
{ "xAxesListings": "61e048080589f874231c1a85",  "xAxesProducts": 0}, 
{ "xAxesListings": "61e048080589f874231c1a85",   "xAxesProducts": 1},
{ "xAxesListings": "61e048080589f874231c1a85",  "xAxesProducts": 2}
{ "xAxesListings": "61f7000ea4f1662e206d5c0f",   "xAxesProducts": 0}
]

what I have tried so far

  var result = Object.keys(countRentals).map(function(e) {
    return countRentals[e];

but i am getting this where I have a lot of values with zero that I don't need.

[
    [
        {
            "xAxesListings": "61e045a8bd8e57666714c413",
            "xAxesProducts": 0
        }
    ],
   
   
        {
            "xAxesListings": "61e048080589f874231c1a85",
            "xAxesProducts": 2
        }
    ],
    [
        {
            "xAxesListings": "61e1763538ee44ada3c955fb",
            "xAxesProducts": 0
        },
        0
    ],
    [
        {
            "xAxesListings": "61e1770138ee44ada3c95604",
            "xAxesProducts": 0
        },
        0
    ],
    [
        0
    ],
    [
        0,
        0
    ],
   
      });

I also have tried this:

 var arr = Object.entries(countRentals);

and in this case I am getting this:

[
    [
        "61e045a8bd8e57666714c413",
        [
            {
                "xAxesListings": "61e045a8bd8e57666714c413",
                "xAxesProducts": 0
            }
        ]
    ],
    [
        "61e0474843bbc2ab0d553633",
        [
            {
                "xAxesListings": "61e0474843bbc2ab0d553633",
                "xAxesProducts": 0
            }
        ]
    ],
2
  • Sounds good. What have you tried? Making an attempt is important - it shows you are trying to learn and shows others where you need help. Commented Feb 2, 2022 at 22:16
  • @Kinglish I added with the things I have tried and the results I got. Commented Feb 2, 2022 at 22:25

1 Answer 1

1

One of the possible solutions could look as follows:

Object.values(yourStructure)
    .flat()
    .filter(v => typeof v === 'object');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.