0

This is my code

let array = [
  [
    ['firstName', 'Mary'],
    ['lastName', 'Jenkins'],
    ['age', 36],
    ['gender', 'female'],
  ],
  [
    ['lastName', 'Kim'],
    ['age', 40],
    ['gender', 'female'],
  ],  [
    ['firstName', 'Joe'],
    ['age', 42],
    ['gender', 'male'],
  ],
]

array.map(function (el) {
   return Object.assign({}, el)
})

However this is how it appears in the console

enter image description here

I've tried array.flat() but did not work as intended

I want the result to look something like this

[[{firstName : 'Mary'}.{lastName : 'jenkins'},..],...]

2 Answers 2

1

Do you want a list of objects, or a list of a list of key-value (pair) objects?

List of objects

let array = [
  [
    ['firstName', 'Mary'],
    ['lastName', 'Jenkins'],
    ['age', 36],
    ['gender', 'female'],
  ],
  [
    ['lastName', 'Kim'],
    ['age', 40],
    ['gender', 'female'],
  ],  [
    ['firstName', 'Joe'],
    ['age', 42],
    ['gender', 'male'],
  ],
]

const listOfObjects = array.map(Object.fromEntries);

console.log(listOfObjects.map(JSON.stringify).join('\n'));
.as-console-wrapper { top: 0; max-height: 100% !important; }

List of list of object properties

let array = [
  [
    ['firstName', 'Mary'],
    ['lastName', 'Jenkins'],
    ['age', 36],
    ['gender', 'female'],
  ],
  [
    ['lastName', 'Kim'],
    ['age', 40],
    ['gender', 'female'],
  ],  [
    ['firstName', 'Joe'],
    ['age', 42],
    ['gender', 'male'],
  ],
]

const listOfListOfPairs = array.map(items =>
  items.map(item =>
    Object.fromEntries([item])));

console.log(listOfListOfPairs.map(JSON.stringify).join('\n'));
.as-console-wrapper { top: 0; max-height: 100% !important; }

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

Comments

1

you can use Object.fromEntries.

in your case something like this would work:

let array = [
  [
    ['firstName', 'Mary'],
    ['lastName', 'Jenkins'],
    ['age', 36],
    ['gender', 'female'],
  ],
  [
    ['lastName', 'Kim'],
    ['age', 40],
    ['gender', 'female'],
  ],  [
    ['firstName', 'Joe'],
    ['age', 42],
    ['gender', 'male'],
  ],
]

const asObjects = array.map((entries) => Object.fromEntries(entries))
console.log(asObjects)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.