我需要在对象数组中找到一个键并将其与Regex匹配

时间:2017-03-13 21:57:36

标签: javascript arrays json regex object

我已经失去了3天以上但仍然没有成功。这可能就像在大海捞针一样,但我仍然需要这样做。

我正在尝试在对象数组中找到键,如果它包含(a)(b),则将某个键设置为true

然而,我在某处犯了一个错误,但我不知道在哪里。

以下是我现在所拥有的:

let reg = /\((.+?)\)/;
let aggregatedArray: Array<any> = [];
const allWeeksDescription = this.selectedPlan.weeklyOffer;
console.log(allWeeksDescription);
let prop = 'description';
for (prop in allWeeksDescription) {
    allWeeksDescription[prop].forEach(function(k:any) {
          aggregatedArray.push(k.description);
          console.log(aggregatedArray);
     })
}

但是,我在控制台中收到此错误(但是,我确实得到了console.log成功):

  

原始例外:allWeeksDescription [prop] .forEach不是   功能

我需要做的就是找到key ('description'),如果它的值与RegEx成功匹配,则将另一个key ('exists')设置为true。如果没有,请保持原样 - false。应使用存储在此变量中的RegEx进行匹配:

let reg = /\((.+?)\)/;

在控制台中我收到这样的内容:

{
   monday: [
         {
            description: "(a)",
            exists: false
         },
         {
            description: "(a)",
            exists: false
         },
         {
            description: "(a)",
            exists: false
         },
         {
            description: "(a)",
            exists: false
         },
         {
            description: "(a)",
            exists: false
         }
        ]
tuesday:  [
         {
            description: "test",
            exists: false
         },
         {
            description: "test",
            exists: false
         },
         {
            description: "test",
            exists: false
         },
         {
            description: "test",
            exists: false
         },
         {
            description: "test",
            exists: false
         }
        ]
     }

总之,我需要获取description keys并将其与Regex匹配。如果匹配,则key exists的值应为true。如果没有,它应该保持原样 - false

请帮助我,我已经失去了太多天。

谢谢你们。

2 个答案:

答案 0 :(得分:1)

以下是如何在匿名类型对象上运行foreach循环。你需要做的是获取对象的所有键,并假设它们具有相同的结构,你需要确保它们与模式匹配。

&#13;
&#13;
let reg = /\((.+?)\)/;
let aggregatedArray = [];
const allWeeksDescription = this.selectedPlan.weeklyOffer;
console.log(allWeeksDescription);
let prop = 'description';
Object.keys(allWeeksDescription).forEach(function(k) {
    reg.match(allWeeksDescription[k]) && aggregatedArray.push(k.description);
    console.log(aggregatedArray);
})
&#13;
&#13;
&#13;

答案 1 :(得分:1)

如果您在帖子底部描述的对象为allWeeksDescription,那么您需要将for循环更改为:

  let matchingDays = []; // to keep a track of matching days
  for(let dayLabel in allWeeksDescription) {
      /* This is one day (= an array), in your first object */
      let day = allWeeksDescription[dayLabel];
      /* Go through all of its elements */
      day.forEach( d => {
        /* `d` is one element of the array */

        /* Check if it matches your regex */
        if(d.description.search(reg) !== -1) {
          /* do whatever you want here, you know that the description matches your regex */
          d.exists = true;
          matchingDays.push(day);
        }
      });
    }