Home > OS >  Find an alternative to split when processing a lot of data
Find an alternative to split when processing a lot of data

Time:06-25

I am mapping through the object in order to return an array of object. However I want to modify the "model-1111" from a string to an integer. This method works with a split, however I would like to find an alternative to split, because split will return an array, which is not the best when processing a lot of data.

const data = { "model-10389": 164703, "model-10388": 164704, "model-10387": 164705 };

const output = Object.entries(data).map(([key, id]) => ({
  modelId:  key.split("-").pop(),
  id
}));

console.log(output);

CodePudding user response:

You could limit the split activities by supplying the second (optional) argument.

const data = {"model-10389-extra": 164703,  "model-10388": 164704,  "model-10387": 164705};

  const output = Object.entries(data).map(([key, id]) => ({
  modelId:  key.split("-",2)[1],
  id
  }));

 console.log(output);

CodePudding user response:

You can slice() or substring() the string from the indexOf() the '-'

const data = { "model-10389": 164703, "model-10388": 164704, "model-10387": 164705 };

const output = Object.entries(data).map(([key, id]) => ({
  modelId:  key.slice(key.indexOf("-")   1),
  id
}));

console.log(output);

Or using RegExp to find the trailing digits (\d $)

const data = { "model-10389": 164703, "model-10388": 164704, "model-10387": 164705 };

const output = Object.entries(data).map(([key, id]) => ({
  modelId:  key.match(/\d $/),
  id
}));

console.log(output);

Or, as I believe Nina Scholz was hinting at in the comments, you could simply replace() the prefix with an empty string.

const data = { "model-10389": 164703, "model-10388": 164704, "model-10387": 164705 };

const output = Object.entries(data).map(([key, id]) => ({
  modelId:  key.replace('model-', ''),
  id
}));

console.log(output);

  • Related