How to use nested object values ​and keys

46 Views Asked by At

How to convert a function to get a response with structure when nested objects

{
 array[0][key]: array[0],
 array[1][key]: array[1],

_${key}s: [array[0][key], array[1][key]]
}

I get the desired answer for non-nested objects (based on this answer)

function mapByKey(array, key) {
  if (array == null) {
    return `Invalid array`;
  }

  const result = { [`_${key}s`]: [] };

  for (const o of array) {
    if (Object.hasOwn(o, key)) {
      const keyValue = o[key].toString();

      if (!Object.hasOwn(result, keyValue)) {
        result[`_${key}s`].push(keyValue);
      }

      result[keyValue] = o;
    }
  }

  return result;
}

for example an array like this

const array = [
  {
    id: 1,
    age: 25,
    address: {
      city: "New York",
      zipCode: 10001,
    },
    name: "John",
    surname: "Doe",
  },
  {
    id: 2,
    age: 30,
    address: {
      city: "Los Angeles",
      zipCode: 90001,
    },
    name: "Jane",
    surname: "Smith",
  },
];

mapByKey(array, city)

Limitations and warranties: - it is guaranteed that the key values ​​of objects in the array (and nested objects) have only the following data types: +string; +number; +null; +undefined; + boolean; - recommended time complexity of the function is O(n). - the array parameter can take the values ​​null or undefined - in this case, the function execution should not fail with an error. - if the key argument is not among the keys of array objects, the function must return a structure of the form

{
  _${key}s: [];
}
0

There are 0 best solutions below