-3

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;
}
chrslg
  • 9,023
  • 5
  • 17
  • 31
Julian
  • 411
  • 4
  • 18

3 Answers3

0

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"
  }
}

and you can still access it like a array

toObject(arr)[0][0]  // "r"

//or

toObject(arr).1.2    // "i"
Laaouatni Anas
  • 4,199
  • 2
  • 7
  • 26
0

You can use Array.prototype.reduce to transform your array into an array of different shape of an object

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

const results = data.reduce((accumulator, current) => {
  let obj = current.reduce((acc, curr, index) => {
    acc[curr] =  index;
    return acc;
  }, {});
  accumulator = accumulator.concat(obj);
  return accumulator;
}, []);

console.log(results);
Yves Kipondo
  • 5,289
  • 1
  • 18
  • 31
-1

here is what you are looking for :


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

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

coderpolo
  • 307
  • 3
  • 12
  • If you are not sure then why did you answer? Please provide an explanation for your answers too. Otherwise they are not very useful – Dharman Oct 17 '22 at 15:53
  • its not difficult to run the js in an emulator and see that its what the OP wanted but the keys need to be tweaked a bit, to you want the unit tests aswell or what :'D – coderpolo Oct 17 '22 at 19:54
  • Please read [answer]. – Dharman Oct 17 '22 at 19:58