简体   繁体   English

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

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

I have an array of objects that i need to flatten/simplify/combine based on certain conditions.我有一组对象,我需要根据某些条件展平/简化/组合这些对象。 Here is the shape of my current array of objects below:下面是我当前对象数组的形状:

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'  ] } 
  ] ]

I basically want this arrayOfObjects to be shaped into this structure:我基本上希望这个 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' ] 
    } 
  ] 

As you can see i'm basically wanting to combine the modules and batteries details into one object, then as you can see i want to create another object within that array once i hit the {"assetSeparator": "assetSeparator"} .如您所见,我基本上是想将模块和电池详细信息合并到一个 object 中,然后如您所见,一旦我点击{"assetSeparator": "assetSeparator"} ,我就想在该数组中创建另一个 object。 That's like my conditional that tells me that asset has been combined, now time to combine the next one, almost think of it as string.split("assetSeparator")这就像我的条件告诉我资产已经合并,现在是时候合并下一个资产了,几乎可以将其视为string.split("assetSeparator")

Can someone please tell me how i could achieve this, i've tried Object.assign({}, ...arrayOfObjects) but that didn't quite achieve what i want, and i can't detect the {"assetSeparator": "assetSeparator"} using the spread operator.有人可以告诉我如何实现这一点,我已经尝试过Object.assign({}, ...arrayOfObjects)但这并没有完全达到我想要的效果,而且我无法检测到{"assetSeparator": "assetSeparator"}使用扩展运算符。

I've also tried doing a reduce arrayOfObjects.reduce(function(result, current) { return Object.assign(result, current); }, {}) but because it's accumulating an object, it's just override object properties with the same keys.我也尝试过减少arrayOfObjects.reduce(function(result, current) { return Object.assign(result, current); }, {})但因为它正在累积 object,所以它只是用相同的键覆盖 object 属性. Please help.请帮忙。

Please note, that your required output is IMPOSSIBLE - but if there's more than one object with the same key, the output could have an array of values for that key - see code请注意,您所需的 output 是不可能的 - 但如果有多个 object 具有相同的密钥,则 output 可能具有该密钥的一组值- 请参阅代码

If each group of items in the original array begins with an object with a single key "Battery" - then this will perform the majicks for you如果原始数组中的每组项目都以 object 和一个键“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; }

You can try something like this你可以尝试这样的事情

 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)

You can group them based on the key of an object ie assetSeparator您可以根据 object 的键对它们进行分组,即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; }

Another one solution.另一种解决方案。 You can use hash grouping approach to combine objects by condition.您可以使用 hash 分组方法按条件组合对象。

 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}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在另一个数组中的对象内的一个对象数组中添加对象内容 - Add object contents in one object array within objects in another array 将一组对象组合成一个 OBJECT - Combine an array of objects into one OBJECT 根据另一个数组 Object 作为条件过滤对象数组 - Filter the Array of objects based on another Array Object as condition 如何在对象数组中组合类似的对象并插入新的 object? - How to combine like objects within array of objects and insert new object? 如何用另一个对象数组更改一个对象数组中的对象值? - How to change object value within an array of objects with one from another array of objects? 如何基于对象数组创建新对象 - How to create a new Object based on an array of objects 如何将具有相同键的对象数组合到一个对象中? - How can I combine an array of objects with the same keys into one object? 根据JavaScript中的条件将对象拆分为对象数组 - Split an object into array of objects based on a condition in JavaScript 如何根据另一个数组对象的某些属性创建一个对象数组? - How can I create an array of objects based on some of another array object's properties? 更改对象中值的状态,在对象数组中的索引处,在对象中? - Changing state of a value in an object, at an index within an array of objects, within a object?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM