如何将对象数组组合成一个对象,然后根据索引条件在该数组中创建另一个对象

How to combine array of objects into one object and then create another object within that array based on a condition on the index

我有一组对象,我需要根据特定条件 flatten/simplify/combine。下面是我当前对象数组的形状:

const arrayOfObjects = 
  [ { Battery           : 'Battery'        } 
  , { batteryDetailsKey : [ 'Serial Number', 'Type', 'Part Number'       ] } 
  , { batteryDetailsVal : [ 'HJ3CA19347410218LJ98 100 QC', 'Extended Range', '4P94-Q001' ] } 
  , { Modules           : 'Modules'        } 
  , { moduleDetailsKey  : [ 'Serial Number', 'Part Number', 'Cell Count' ] } 
  , { moduleDetailsVal  : [ '83675327350061093222581609899001', 'LJ98-10C779-A01', '32'  ] } 
  , { assetSeparator    : 'assetSeparator' } 
  , { Battery           : 'Battery'        }  
  , { batteryDetailsKey : [ 'Serial Number', 'Type', 'Part Number'       ] } 
  , { batteryDetailsVal : [ 'HJ3CA19347410218LJ98 101 QC', 'Extended Range', '4P94-Q002' ] } 
  , { Modules           : 'Modules'        } 
  , { moduleDetailsKey  : [ 'Serial Number', 'Part Number', 'Cell Count' ] } 
  , { moduleDetailsVal  : [ '83675327350061093222581609899002', 'LJ98-10C779-A02', '28'  ] } 
  , { moduleDetailsVal  : [ '83675327350061093222581609899003', 'LJ98-10C779-A03', '27'  ] } 
  , { assetSeparator    : 'assetSeparator' } 
  , { Battery           : 'Battery'        } 
  , { batteryDetailsKey : [ 'Serial Number', 'Type', 'Part Number'                       ] } 
  , { batteryDetailsVal : [ 'HJ3CA19347410218LJ98 102 QC', 'Extended Range', '4P94-Q003' ] } 
  , { Modules           : 'Modules'        } 
  , { moduleDetailsKey  : [ 'Serial Number', 'Part Number', 'Cell Count' ] } 
  , { moduleDetailsVal  : [ '83675327350061093222581609899004', 'LJ98-10C779-A01', '32'  ] } 
  ] ]

我基本上希望这个 arrayOfObjects 被塑造成这个结构:

const shapeIWantArrayOfObjects = 
  [ { Battery           : 'Battery'
    , batteryDetailsKey : [ 'Serial Number', 'Type', 'Part Number' ] 
    , batteryDetailsVal : [ 'HJ3CA19347410218LJ98 100 QC', 'Extended Range', '4P94-Q001' ] 
    , Modules           : 'Modules'
    , moduleDetailsKey  : [ 'Serial Number', 'Part Number', 'Cell Count' ] 
    , moduleDetailsVal  : [ '83675327350061093222581609899001', 'LJ98-10C779-A01', '32' ] 
    } 
  , { Battery           : 'Battery'
    , batteryDetailsKey : [ 'Serial Number', 'Type', 'Part Number' ] 
    , batteryDetailsVal : [ 'HJ3CA19347410218LJ98 101 QC', 'Extended Range', '4P94-Q002' ] 
    , Modules           : 'Modules'
    , moduleDetailsKey  : [ 'Serial Number', 'Part Number', 'Cell Count'] 
    , moduleDetailsVal  : [ '83675327350061093222581609899002', 'LJ98-10C779-A02', '28' ] 
    , moduleDetailsVal  : [ '83675327350061093222581609899003', 'LJ98-10C779-A03', '27' ] 
    } 
  , { Battery           : 'Battery'
    , batteryDetailsKey : [ 'Serial Number', 'Type', 'Part Number' ] 
    , batteryDetailsVal : [ 'HJ3CA19347410218LJ98 102 QC', 'Extended Range', '4P94-Q003' ] 
    , Modules           : 'Modules'
    , moduleDetailsKey  : [ 'Serial Number', 'Part Number', 'Cell Count'] 
    , moduleDetailsVal  : [ '83675327350061093222581609899004', 'LJ98-10C779-A01', '32' ] 
    } 
  ] 

如您所见,我基本上是想将模块和电池详细信息组合到一个对象中,然后如您所见,我想在点击 {"assetSeparator": "assetSeparator"} 后在该数组中创建另一个对象。这就像我的条件告诉我资产已经合并,现在是时候合并下一个资产了,几乎可以将其视为 string.split("assetSeparator")

有人能告诉我如何实现这一点吗,我已经尝试过 Object.assign({}, ...arrayOfObjects) 但那并没有完全达到我想要的效果,而且我无法检测到 {"assetSeparator": "assetSeparator"} 使用传播运算符。

我也试过做一个 reduce arrayOfObjects.reduce(function(result, current) { return Object.assign(result, current); }, {}) 但因为它正在累积一个对象,它只是用相同的键覆盖对象属性。请帮忙。

请注意,您所需的输出是不可能的 - 但如果有多个对象具有相同的键,则输出可能包含该键的一组值 - 请参阅代码

如果原始数组中的每组项目都以具有单个键“Battery”的对象开头 - 那么这将为您执行 majicks

const arrayOfObjects = [{"Battery": "Battery"},{"batteryDetailsKey": ["Serial Number","Type","Part Number",]},{"batteryDetailsVal": ["HJ3CA19347410218LJ98 100 QC","Extended Range","4P94-Q001",]},{"Modules": "Modules"},{"moduleDetailsKey": ["Serial Number","Part Number","Cell Count",]},{"moduleDetailsVal": ["83675327350061093222581609899001","LJ98-10C779-A01","32",]},{"assetSeparator": "assetSeparator"},{"Battery": "Battery"},{"batteryDetailsKey": ["Serial Number","Type","Part Number"]},{"batteryDetailsVal": ["HJ3CA19347410218LJ98 101 QC","Extended Range","4P94-Q002"]},{"Modules": "Modules"},{"moduleDetailsKey": ["Serial Number","Part Number","Cell Count"]},{"moduleDetailsVal": ["83675327350061093222581609899002","LJ98-10C779-A02","28"]},{"moduleDetailsVal": ["83675327350061093222581609899003","LJ98-10C779-A03","27"]},{"assetSeparator": "assetSeparator"},{"Battery": "Battery"},{"batteryDetailsKey": ["Serial Number","Type","Part Number",]},{"batteryDetailsVal": ["HJ3CA19347410218LJ98 102 QC","Extended Range","4P94-Q003",]},{"Modules": "Modules"},{"moduleDetailsKey": ["Serial Number","Part Number","Cell Count",]},{"moduleDetailsVal": ["83675327350061093222581609899004","LJ98-10C779-A01","32",]}];

const shapeIWantArrayOfObjects = [];
let currentOutput;
for (let object of arrayOfObjects) {
    if (Object.keys(object).join('') === 'Battery') {
        currentOutput = {};
        shapeIWantArrayOfObjects.push(currentOutput);
    }
    Object.entries(object).forEach(([key, val]) => {
        const existing = currentOutput[key];
        if (!existing) {
            currentOutput[key] = val;
        } else {
            if (!Array.isArray(currentOutput[key][0])) {
                currentOutput[key] = [currentOutput[key]];
            }
            currentOutput[key].push(val);
        }
    });
}
console.log(shapeIWantArrayOfObjects);
.as-console-wrapper {max-height: 100%!important; top:0; }
.as-console-row::after { display:none !important; }

你可以试试这样的

const arrayOfObjects = [{"Battery": "Battery"}, {"batteryDetailsKey": ["Serial Number", "Type", "Part Number", ] }, {"batteryDetailsVal": ["HJ3CA19347410218LJ98 100 QC", "Extended Range", "4P94-Q001", ] }, {"Modules": "Modules"}, {"moduleDetailsKey": ["Serial Number", "Part Number", "Cell Count", ] }, {"moduleDetailsVal": ["83675327350061093222581609899001", "LJ98-10C779-A01", "32", ] }, {"assetSeparator": "assetSeparator"}, {"Battery": "Battery"}, {"batteryDetailsKey": ["Serial Number", "Type", "Part Number"] }, {"batteryDetailsVal": ["HJ3CA19347410218LJ98 101 QC", "Extended Range", "4P94-Q002"] }, {"Modules": "Modules"}, {"moduleDetailsKey": ["Serial Number", "Part Number", "Cell Count"] }, {"moduleDetailsVal": ["83675327350061093222581609899002", "LJ98-10C779-A02", "28"] }, {"moduleDetailsVal": ["83675327350061093222581609899003", "LJ98-10C779-A03", "27"] }, {"assetSeparator": "assetSeparator"}, {"Battery": "Battery"}, {"batteryDetailsKey": ["Serial Number", "Type", "Part Number", ] }, {"batteryDetailsVal": ["HJ3CA19347410218LJ98 102 QC", "Extended Range", "4P94-Q003", ] }, {"Modules": "Modules"}, {"moduleDetailsKey": ["Serial Number", "Part Number", "Cell Count", ] }, {"moduleDetailsVal": ["83675327350061093222581609899004", "LJ98-10C779-A01", "32", ] }];

let shapeIWantArrayOfObjects = [], tempObj = {}, i = 0;
arrayOfObjects.forEach(obj => {
    if( !obj.hasOwnProperty('assetSeparator') ){
        shapeIWantArrayOfObjects[i] = { ...shapeIWantArrayOfObjects[i], ...obj };
    }else{
        i++;
        tempObj = {};
    }
});

console.log(shapeIWantArrayOfObjects)

您可以根据对象的键对它们进行分组,即 assetSeparator

const result = arrayOfObjects.reduce((acc, curr) => {
  if (new Set(Object.keys(curr)).has('assetSeparator')) {
    acc.push({});
  } else {
    if (!acc.length) acc.push({ ...curr });
    else {
      const last = acc[acc.length - 1];
      Object.keys(curr).forEach((k) => {
        last[k] = curr[k];
      });
    }
  }
  return acc;
}, []);

const arrayOfObjects = [
  {
    Battery: 'Battery',
  },
  {
    batteryDetailsKey: ['Serial Number', 'Type', 'Part Number'],
  },
  {
    batteryDetailsVal: [
      'HJ3CA19347410218LJ98 100 QC',
      'Extended Range',
      '4P94-Q001',
    ],
  },
  {
    Modules: 'Modules',
  },
  {
    moduleDetailsKey: ['Serial Number', 'Part Number', 'Cell Count'],
  },
  {
    moduleDetailsVal: [
      '83675327350061093222581609899001',
      'LJ98-10C779-A01',
      '32',
    ],
  },
  {
    assetSeparator: 'assetSeparator',
  },

  {
    Battery: 'Battery',
  },
  {
    batteryDetailsKey: ['Serial Number', 'Type', 'Part Number'],
  },
  {
    batteryDetailsVal: [
      'HJ3CA19347410218LJ98 101 QC',
      'Extended Range',
      '4P94-Q002',
    ],
  },
  {
    Modules: 'Modules',
  },
  {
    moduleDetailsKey: ['Serial Number', 'Part Number', 'Cell Count'],
  },
  {
    moduleDetailsVal: [
      '83675327350061093222581609899002',
      'LJ98-10C779-A02',
      '28',
    ],
  },
  {
    moduleDetailsVal: [
      '83675327350061093222581609899003',
      'LJ98-10C779-A03',
      '27',
    ],
  },
  {
    assetSeparator: 'assetSeparator',
  },
  {
    Battery: 'Battery',
  },
  {
    batteryDetailsKey: ['Serial Number', 'Type', 'Part Number'],
  },
  {
    batteryDetailsVal: [
      'HJ3CA19347410218LJ98 102 QC',
      'Extended Range',
      '4P94-Q003',
    ],
  },
  {
    Modules: 'Modules',
  },
  {
    moduleDetailsKey: ['Serial Number', 'Part Number', 'Cell Count'],
  },
  {
    moduleDetailsVal: [
      '83675327350061093222581609899004',
      'LJ98-10C779-A01',
      '32',
    ],
  },
];

const result = arrayOfObjects.reduce((acc, curr) => {
  if (new Set(Object.keys(curr)).has('assetSeparator')) {
    acc.push({});
  } else {
    if (!acc.length) acc.push({ ...curr });
    else {
      const last = acc[acc.length - 1];
      Object.keys(curr).forEach((k) => {
        last[k] = curr[k];
      });
    }
  }
  return acc;
}, []);

console.log(result);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }

另一种解决方案。您可以使用散列分组方法按条件组合对象。

const arrayOfObjects = [{"Battery":"Battery"},{"batteryDetailsKey":["Serial Number","Type","Part Number"]},{"batteryDetailsVal":["HJ3CA19347410218LJ98 100 QC","Extended Range","4P94-Q001"]},{"Modules":"Modules"},{"moduleDetailsKey":["Serial Number","Part Number","Cell Count"]},{"moduleDetailsVal":["83675327350061093222581609899001","LJ98-10C779-A01","32"]},{"assetSeparator":"assetSeparator"},{"Battery":"Battery"},{"batteryDetailsKey":["Serial Number","Type","Part Number"]},{"batteryDetailsVal":["HJ3CA19347410218LJ98 101 QC","Extended Range","4P94-Q002"]},{"Modules":"Modules"},{"moduleDetailsKey":["Serial Number","Part Number","Cell Count"]},{"moduleDetailsVal":["83675327350061093222581609899002","LJ98-10C779-A02","28"]},{"moduleDetailsVal":["83675327350061093222581609899003","LJ98-10C779-A03","27"]},{"assetSeparator":"assetSeparator"},{"Battery":"Battery"},{"batteryDetailsKey":["Serial Number","Type","Part Number"]},{"batteryDetailsVal":["HJ3CA19347410218LJ98 102 QC","Extended Range","4P94-Q003"]},{"Modules":"Modules"},{"moduleDetailsKey":["Serial Number","Part Number","Cell Count"]},{"moduleDetailsVal":["83675327350061093222581609899004","LJ98-10C779-A01","32"]}];

let objectCount = 0;
const shapeIWantArrayOfObjects = Object.values(arrayOfObjects.reduce((acc, item) => {
  if (item.assetSeparator === "assetSeparator") {
    objectCount += 1;
    return acc;
  }
  acc[objectCount] ??= {};
  acc[objectCount] = { ...acc[objectCount], ...item };
  
  return acc;
}, {}));

console.log(shapeIWantArrayOfObjects);
.as-console-wrapper{min-height: 100%!important; top: 0}