从简单数组创建嵌套对象

我正在尝试从一个简单的数组中创建一个深层嵌套的 JS 对象。棘手的部分是数组中的下一项应始终添加到前一项。

假设我的数组如下所示:

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

如何获得具有该结构的对象?

    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
          }
        }
      }
    },

如何实现将新的“或”块添加到前一个“或”块?

回答

您可以在遍历数组时构建嵌套结构。对于每个项目,添加一个嵌套对象,其中包含一个or链接到该项目的键,并且每个后续迭代都在前一个项目上工作

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


以上是从简单数组创建嵌套对象的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>