-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);
7
  • 3
    What did you try? Commented Dec 3, 2021 at 12:56
  • You should add minimal reproducible code, so that people can understand your problem and help you. see why you shouldn't post image as a code or an error Commented Dec 3, 2021 at 12:57
  • i've tried using foreach, but failed Commented Dec 3, 2021 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 Commented Dec 3, 2021 at 12:57
  • 2
    i've eddited the post so u can see what i've tried Commented Dec 3, 2021 at 12:59

2 Answers 2

1

You can use Object.fromEntries()

const data = [['name', 'marcus'], ['address', 'New York']];
const result = Object.fromEntries(data);
console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

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));

1 Comment

@MarcusRibas Not a problem, Glas I could help

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.