使用数组元素创建对象而不覆盖现有键

Creating Object Using Array Elements without overwriting Existing Keys

我试图从包含许多数组的数组创建对象。 数组元素是彼此嵌套的对象键,前提是键最初没有创建。也就是说,它不应该覆盖密钥并且还应该维护密钥索引。

例子是这样的-


const MainArray = [
                    {
                      key: ['name', 'dog', 'feature', 'hairy'],
                      value1:1 , 
                      value2:2
                     },
                    {
                      key: ['name', 'dog', 'eye', 'brown'],
                      value1:1 , 
                      value2:2
                     }, 
                    {
                      key: ['kind', 'human', 'class', 'man', 'height', 'tall'],
                      value1:'Mike' , 
                      value2:'John'
                     }, 
                     {
                      key: ['kind', 'human', 'class', 'woman', 'hobby'],
                      value1:'Cyling' , 
                      value2:'Tennis'
                     }, 

                ]


const requiredObject = 
                     {

                      name:{
                          dog :{
                            feature:{
                                   hairy :{value1:1, value2:2}
                            },
                            eye:{
                                brown:{value1:1, value2:2}
                             }
                           }
                        },
                        kind:{
                           human:{
                              class:{
                                   man:{
                                      height:{
                                        tall:{value1:'Mike', value2:'John'}
                                      }
                                   },
                                   woman:{
                                       hobby:{value1:'Cyling', value2: 'Tennis'}
                                   } 
                                }
                            }
                         }

                     }

我怎样才能从 MainArrayrequireObject

您可以使用 array.reduce() 通过使用另一个 array.reduce() 遍历 key 个数组来构建新对象。尝试:

const MainArray = [
    {
      key: ['name', 'dog', 'feature', 'hairy'],
      value1:1 , 
      value2:2
     },
    {
      key: ['name', 'dog', 'eye', 'brown'],
      value1:1 , 
      value2:2
     }, 
    {
      key: ['kind', 'human', 'class', 'man', 'height', 'tall'],
      value1:'Mike' , 
      value2:'John'
     }, 
     {
      key: ['kind', 'human', 'class', 'woman', 'hobby'],
      value1:'Cyling' , 
      value2:'Tennis'
     }
];


const result = MainArray.reduce((acc, cur) => {
    let { key, ...data } = cur;
    let lastIndex = key.length - 1;

    key.reduce((obj, k, index) => {
        obj[k] = obj[k] || (index === lastIndex ? {...data}  : {});
        return obj[k];
    }, acc);

    return acc;
}, {});

console.log(result);