1

I have some objects

var officers = [
  { id: 20, name: 'Captain Piett' },
  { id: 24, name: 'General Veers' },
  { id: 56, name: 'Admiral Ozzel' },
  { id: 88, name: 'Commander Jerjerrod' }
];

I need to return "20","24","56","88"

Now I'm using

const ids = officers.map(officer => officer.id);

but it return me an array of course.

What's the most efficient way?

0

3 Answers 3

4

You can use map() to return array of string with "" and then use join()

var officers = [
  { id: 20, name: 'Captain Piett' },
  { id: 24, name: 'General Veers' },
  { id: 56, name: 'Admiral Ozzel' },
  { id: 88, name: 'Commander Jerjerrod' }
];

const res = officers.map(x => `"${x.id}"`).join()

console.log(res)

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

Comments

0

You can surround by quotes on map and then call Array.join.

const ids = officers.map(officer => '"' + officer.id + '"').join();

Comments

0

What's the most efficient way?

Array.map creates each time a new function and calls it, thats not efficient.

The most efficient way is to use plain for-loops:

var res = '';
for(let {id} in officers){ 
 res+=....
}

But now you would create each time a new string (res+=...). Thats absolutely ok if you don't have to handle alot of strings, but in the case you do you may want to switch to arrays and join it into a string at the end.

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.