Bart
Bart

Reputation: 515

Create a nested Object from simple Array

I'm trying to create a deep nested JS Object out of a simple array. The tricky part is that the next item in the array should always be added to the previous one.

Assuming my array looks like this:

const filters = [
    [
        {brand: {eq: 'BMW'}},
        {brand: {eq: 'AUDI'}}
    ],
    [
        {year: {eq: '2019'}},
        {year: {eq: '2020'}}
    ],
    [
        {country: {eq: 'CH'}},
        {country: {eq: 'DE'}}
    ]
]

How can I get a Object with that structure?

    query: {
      and: {
        or: [
          { brand: { eq: 'BMW' } },
          { brand: { eq: 'AUDI' } }
        ],
        and: {
          or: [
            { year: { eq: '2019' } },
            { year: { eq: '2020' } }
          ],
          and: {
            or: [
              { country: { eq: 'CH' } },
              { country: { eq: 'DE' } }
            ],
            ... and so on
          }
        }
      }
    },

How do I achieve to add a new "or" block to the previous "or" block?

Upvotes: 1

Views: 71

Answers (2)

sp00m
sp00m

Reputation: 48807

Just for the reduce challenge:

const filters = [
    [
        {brand: {eq: 'BMW'}},
        {brand: {eq: 'AUDI'}}
    ],
    [
        {year: {eq: '2019'}},
        {year: {eq: '2020'}}
    ],
    [
        {country: {eq: 'CH'}},
        {country: {eq: 'DE'}}
    ]
];

const query = {};
filters.reduce((x, or) => x.and = { or }, query);

console.log(query);

Hacky as hell though:

  • reduce with side-effects
  • returns an assignment

VLAZ's approach is the way to go.

Upvotes: 1

VLAZ
VLAZ

Reputation: 28971

You can build up a nested structure as you go through the array. For each item, add a nested object with an or key that links to the item and each following iteration work on the previous item

const filters = [
    [
        {brand: {eq: 'BMW'}},
        {brand: {eq: 'AUDI'}}
    ],
    [
        {year: {eq: '2019'}},
        {year: {eq: '2020'}}
    ],
    [
        {country: {eq: 'CH'}},
        {country: {eq: 'DE'}}
    ]
]

const query = {};
let current = query;

for (const filter of filters) {
  current.and = { or: filter };
  current = current.and; 
}

console.log(query);

Upvotes: 6

Related Questions