Home > Blockchain >  How to turn 2 arrays into an object with key value pairs
How to turn 2 arrays into an object with key value pairs

Time:03-23

I have an object which contains 2 objects with properties:

const objects = {
  Battery: {
    batteryDetailsKey: ['serial_no', 'type', 'part_no'],
    batteryDetailsVal: [
      'HJ3CA19347410218LJ98 151 QC',
      'Extended Range',
      '4P94-Q051',
    ],
  },
  Modules: {
    moduleDetailsKey: ['serial_no', 'part_no', 'Cell Count'],
    moduleDetailsVal: [
      '8367532735006109322258160 50',
      'LJ98-10C779-A51',
      '32',
      '6',
    ],
  },
};

I need to change the structure of the data to this:

const desiredObject = {
  Battery: {
    'serial_no': 'HJ3CA19347410218LJ98 151 QC',
    'type': 'Extended Range',
    'part_no': '4P94-Q051',
  },
  Modules: {
    'serial_no':'8367532735006109322258160 50',
    'part_no':'LJ98-10C779-A51',
    'cell_count': '32',
  },
};

I have tried

let emptyObject = {}

Object.keys(objects).forEach((q, i) => {
    emptyObject = {
        objects[q] 
    }
})

but isn't quite achieving what i want, any help is welcome. Thanks

CodePudding user response:

I am assuming that:

  • Both arrays will always have equal lengths. OR
  • Keys' array (Array 1) is bigger and you want all the keys from Array 1 and all excess keys will have value undefined. OR
  • Keys' array (Array 1) is smaller and you want to skip all the extra values present in the values' array (Array 2).

You can try the below code, I have used Array reduce() on array 1 and used the index parameter to access the corresponding value in array 2. For looping the objects object I have used Object.keys() and created a new desired object.

So the complete answer for your problem will be something like below:

const objects = {
  Battery: {
    batteryDetailsKey: ["serial_no", "type", "part_no"],
    batteryDetailsVal: ["HJ3CA19347410218LJ98 151 QC", "Extended Range", "4P94-Q051"],
  },
  Modules: {
    moduleDetailsKey: ["serial_no", "part_no", "Cell Count"],
    moduleDetailsVal: ["8367532735006109322258160 50", "LJ98-10C779-A51", "32", "6"],
  },
};

function twoArraysToObject(arr1, arr2) {
  return arr1.reduce((obj, item, index) => {
    obj[item] = arr2[index];
    return obj;
  }, {});
}

const desiredObject = {};
Object.keys(objects).forEach((key) => {
  const keyNamesArr = Object.keys(objects[key]);
  desiredObject[key] = twoArraysToObject(objects[key][keyNamesArr[0]], objects[key][keyNamesArr[1]]);
});

console.log(desiredObject);

CodePudding user response:

You could take the entries of your objects object to get an array of key value pairs. You can then map this array of key value pairs so that each each value is updated to have a new object. This new object can be built using Object.fromEntries() and mapping the array found at the key ending with "DetailsKey" to an array of another set of key-value pairs, where each value is the associated value from the array at the key ending with "DetailsVal" (we can use the index i to grab the corresponding item). You can then wrap your mapped objects's entries in another call to Object.fromEntries(), which will build an object for you from your new key-value pair array:

const objects = { Battery: { batteryDetailsKey: ['serial_no', 'type', 'part_no'], batteryDetailsVal: [ 'HJ3CA19347410218LJ98 151 QC', 'Extended Range', '4P94-Q051', ], }, Modules: { moduleDetailsKey: ['serial_no', 'part_no', 'cell_count'], moduleDetailsVal: [ '8367532735006109322258160 50', 'LJ98-10C779-A51', '32', '6', ], }, };

const res = Object.fromEntries(Object.entries(objects).map(([key, value]) => {
  const innerEntries = Object.entries(value);
  const [, details] = innerEntries.find(([key]) => key.endsWith("DetailsKey"));
  const [, vals] = innerEntries.find(([key]) => key.endsWith("DetailsVal"));
  return [key, Object.fromEntries(details.map((key, i) => [key, vals[i]]))];
}));
console.log(res);

If you're ok with relying on the object property/value order the Object.value() gives you (which has only recently been standardized) then you could remove the .find() calls and grab your keys using indexes:

const objects = { Battery: { batteryDetailsKey: ['serial_no', 'type', 'part_no'], batteryDetailsVal: [ 'HJ3CA19347410218LJ98 151 QC', 'Extended Range', '4P94-Q051', ], }, Modules: { moduleDetailsKey: ['serial_no', 'part_no', 'cell_count'], moduleDetailsVal: [ '8367532735006109322258160 50', 'LJ98-10C779-A51', '32', '6', ], }, };

const res = Object.fromEntries(Object.entries(objects).map(([key, value]) => {
  const [details, vals] = Object.values(value);
  return [key, Object.fromEntries(details.map((key, i) => [key, vals[i]]))];
}));
console.log(res);

  • Related