Home > database >  Convert multidimensional array to object while keeping the same structure
Convert multidimensional array to object while keeping the same structure

Time:10-16

I want to convert

let multiArr = [["r", "s", "p"], ["w", "u", "i"], ... , ["a", "t", "g"]]

to:

let multiObj = {{"r": 0, "s": 1, "p": 2}, {"w": 0, "u": 1, "i": 2}, ... , {"a': 0, "t": 1, "g": 2}}

This doesn't seem to work as it flattens the array into one-dimension. How do I keep the two-dimensional aspect of the object?

function toObject(arr) {
  let multiObj = {};
  for (let i = 0; i < arr.length; i  ) {
    for (let j = 0; j < arr[i].length; j  ) {
      let key = arr[i][j];
      let val = j;
      multiObj[key] = val;
    }
  }
  return multiObj;
}

CodePudding user response:

let multiArr = [
  ["r", "s", "p"],
  ["w", "u", "i"],
  ["a", "t", "g"],
];

console.log(
  toObject(multiArr)
);
<script>
  function toObject(arr) {
    let output = {}

    // child array => object
    arr.forEach((child, i) => {
      output[i] = {...child}
    })

    return output;
  }
</script>

expected result:

{
  "0": {
    "0": "r",
    "1": "s",
    "2": "p"
  },
  "1": {
    "0": "w",
    "1": "u",
    "2": "i"
  },
  "2": {
    "0": "a",
    "1": "t",
    "2": "g"
  }
}

CodePudding user response:

basically the desired out syntax doesn't fit with Objects type because objects are set of key value pairs

let multiObj = {{"r", "s", "p"}, {"w", "u", "i"}, {"a", "t", "g"}}

if {"r", "s", "p"} is a value what will be the key?

{key?:{"r", "s", "p"}}

by the way you can convert any array into object by de-structuring it

let array = [1,2,3,4];
 let obj = {...array}

now indexes of array will becomes key and numbers becomes there values

    {
     0: 1,
     1: 2,
     2: 3,
     3: 4
    }

CodePudding user response:

i am not sure this is what you want :


let multiArr = [["r", "s", "p"], ["w", "u", "i"]];

var objs = multiArr.map(array => ({ 
  0: array[0],
  1: array[1],
  2: array[2],
}));

  • Related