首页 > 解决方案 > Filter array of objects - erase last word in the string

问题描述

I have an array of objects:

[
   {
      barcode: ""
      description: "META AM 29 XX Edition Large"
      description2: ""
      group: "COM20"
   },

   {,
      barcode: ""
      description: "META AM 29 TEAM Large"
      description2: ""
      group: "COM20"
   }
]

I want to get rid of the last word in the description. So the result would be:

[
   {
      barcode: ""
      description: "META AM 29 XX Edition"
      description2: ""
      group: "COM20"
   },

   {,
      barcode: ""
      description: "META AM 29 TEAM"
      description2: ""
      group: "COM20"
   }
]

I am using filter, but I don't understand why it doesn't work:

var filtered = data.filter((val) => {
   return val.description.replace(/\w+[.!?]?$/, '');
})
console.log(filtered)

The log is the exactly same array without any change.

标签: javascriptarraysobjectfilter

解决方案


Try this

let data = [{
    barcode: "",
    description: "META AM 29 XX Edition Large",
    description2: "",
    group: "COM20"
  },

  {
    barcode: "",
    description: "META AM 29 TEAM Large",
    description2: "",
    group: "COM20"
  }
]

let result = data.map(ele => {
  let lastword = ele.description.lastIndexOf(" ");
  ele.description = ele.description.substring(0, lastword);


  return ele;


});

console.log(result)


推荐阅读