Home > Software design >  Select and match the same property names/values from list of objects in a json object
Select and match the same property names/values from list of objects in a json object

Time:12-08

Given the following json object

{
    "Item 1": {
        title: 'Item 1',
        sub: {
            left: {
                prop1: '1',
                prop2: '2',
                prop3: '3',
            },
            right: {
                prop1: '4',
                prop2: '5',
                prop3: '6',
            },
        },
    },
    "Item 2": {
        title: 'Item 2',
        sub: {
            left: {
                prop1: '7',
                prop2: '8',
                prop3: '9',
            },
            right: {
                prop1: '10',
                prop2: '11',
                prop3: '12',
            },
        },
    }
}

I'm trying to match up all of the values in "left" and "right" with each other, for each individual object in the list. There could be more properties (prop4 for example) but the "left" and "right" for a given object will always match.

In this example, the desired outcome would be

[
  [
    [
      "1",
      "4"
    ],
    [
      "2",
      "5"
    ],
    [
      "3",
      "6"
    ]
  ],
  [
    [
      "7",
      "10"
    ],
    [
      "8",
      "11"
    ],
    [
      "9",
      "12"
    ]
  ]
]

I really hate that I'm just asking this with no work in progress code to share. I got as far as looping over the object with Object.Keys, and then managed to select a property by name ("prop1") using Reduce, but I can't get as far as selecting everything.

Thank you for any help and pointers

CodePudding user response:

Here is a fairly straightforward solution calling map() on the Object.values() of the top level object, and then using a utility zip function (see this question for full discussion) to zip the left and right values of the sub property.

const input = { 'Item 1': { title: 'Item 1', sub: { left: { prop1: '1', prop2: '2', prop3: '3', }, right: { prop1: '4', prop2: '5', prop3: '6', }, }, }, 'Item 2': { title: 'Item 2', sub: { left: { prop1: '7', prop2: '8', prop3: '9', }, right: { prop1: '10', prop2: '11', prop3: '12', }, }, }, };

const zip = (...rows) => [...rows[0]].map((_, c) => rows.map((row) => row[c]));

const result = Object.values(input).map(({ sub }) => 
  zip(Object.values(sub.left), Object.values(sub.right)));

console.log(result);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related