0

trying to create string array from key/value below code returns key/value. How do I create string array?

main.js

const array = [{
    "id": "123"
  },
  {
    "id": "124"
  }
]

console.log(Object.values(array));
const strinArray = [];

function convert() {
  for (const val of array) {
    strinArray.push(val);
  }
}

expected

["123","124"];
1
  • Your example should be a runnable snippet. And it should log the result, not the input. Commented Feb 28, 2020 at 15:44

2 Answers 2

3

You can use map to achieve the same.

const array = [
  {"id":"123"},
  {"id":"124"}
]

console.log(array.map(item => item.id))

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

2 Comments

Took my upvote away when you mentioned IE11 and not using polyfills. Mentioning such cases is not necessary and detracts from the answer, IMO.
Well, here you go then.
0

You can use map() method & destructuring for this:

const array = [{ "id": "123" }, { "id": "124" } ]

console.log(array.map(({id}) => id))

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.