-3

method input: (['name', 'marcus'], ['address', 'New York']

method output: {name: marcus, address: New York}

How do i do it?

cont array = [['c','2'],['d','4']];

function objectify()
{
    array.forEach(arrayElement => { for(let i = 0; i<2; i++){
            const obj = Object.assign({array[i][i]}, array[i++])
    }
    return obj;
})

}

console.log(objectify);
  • 3
    What did you try? – 0stone0 Dec 03 '21 at 12:56
  • You should add [minimal reproducible code](https://stackoverflow.com/help/minimal-reproducible-example), so that people can understand your problem and help you. [see why you shouldn't post image as a code or an error](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question#:~:text=You%20should%20not%20post%20code,order%20to%20reproduce%20the%20problem.) – DecPK Dec 03 '21 at 12:57
  • i've tried using foreach, but failed – Marcus Ribas Dec 03 '21 at 12:57
  • @MarcusRibas If it failed, not a problem, just shared what you have tried till now. Even though the code is not working – DecPK Dec 03 '21 at 12:57
  • `data.forEach(d => obj[d[0]] = d[1])` – 0stone0 Dec 03 '21 at 12:58
  • 2
    i've eddited the post so u can see what i've tried – Marcus Ribas Dec 03 '21 at 12:59
  • @MarcusRibas did you try using `fromEntries()` – axtck Dec 05 '21 at 16:11

2 Answers2

1

You can use Object.fromEntries()

const data = [['name', 'marcus'], ['address', 'New York']];
const result = Object.fromEntries(data);
console.log(result);
axtck
  • 3,707
  • 2
  • 10
  • 26
0

1) If you are using forEach then you don't have to use for loop inside it

array.forEach(arrayElement => { for(let i = 0; i<2; i++){
            const obj = Object.assign({array[i][i]}, array[i++])
    }

2) You shouldn't hardcode the length upto which i will run, because it can be of any length.

for(let i = 0; i<2; i++)

If you are using forEach then you should loop over the array and get the key and value and set it into the resultant object.

function objectify(array) {
  const result = {};
  
  array.forEach((o) => {
    const [key, value] = o;
    result[key] = value;
  });

  return result;
}

const array = [
  ["c", "2"],
  ["d", "4"],
];
console.log(objectify(array));
DecPK
  • 24,537
  • 6
  • 26
  • 42