Skip to content Skip to sidebar Skip to footer

What's The Best Way (es6 Allowed) To Extract Values From An Array And Convert Them To A String?

I'm trying to take an array like so: location: [ {Id: '000-000', Name: 'Foo'}, {Id: '000-001', Name: 'Bar'}, ..etc ] What's the most efficient/cleanest way to pull out the

Solution 1:

Use reduce, extracting each Id:

const location2 = [{Id: "000-000", Name: "Foo"}, {Id: "000-001", Name: "Bar"}];
console.log(
  location2.reduce((a, { Id }) =>`${a}&myId=${Id}`, '')
);

While this is pretty clean and only requires iterating over each item once, in terms of efficiency, for loops are still more performant if you have a huge number of items in the array:

const location2 = [{Id: "000-000", Name: "Foo"}, {Id: "000-001", Name: "Bar"}];
let output = '';
for (let i = 0, { length } = location2; i < length; i++) {
  output += '&myId=' + location2[i].Id;
}
console.log(output);

Solution 2:

Using map and join seems efficient enough.

const staticString = "&myId=",
  locationArray = [
    {
      Id: "000-000",
      Name: "Foo"
    },
    {
      Id: "000-001",
      Name: "Bar"
    }
  ],
  result = locationArray.map(({Id}) => staticString + Id).join("");

// or// result = staticString + locationArray.map(({Id}) => Id).join(staticString);console.log(result);

In the alternative, the first staticString may also be changed to "?myId=", since this looks like query parameters.

Post a Comment for "What's The Best Way (es6 Allowed) To Extract Values From An Array And Convert Them To A String?"