在es6-2级中过滤对象数组

时间:2018-07-26 08:12:46

标签: javascript ecmascript-6

我有一个类似于下面的JSON。

[{
    "id": "13000001993",
    "title": "Most Popular",
    "answers": [{
        "id": "13000038079",
        "title": "Price",
      },
      {
        "id": "13000033122",
        "title": "Enrollment",
      }
    ]
  },
  {
    "id": "13000000675",
    "title": "Support Questions",
    "answers": [{
        "id": "13000003646",
        "title": "ADMIN Chat",
      },
      {
        "id": "13000033122",
        "title": "Enrollment",
      }
    ]
  },
  {
    "id": "130000005675",
    "title": "Delivery",
    "answers": [{
      "id": "13000003646",
      "title": "Cost",
    }]
  }
]

我想基于answers过滤外部数组和title。假设如果我的搜索关键字是Enrollment,那么我想仅返回answer的标题(如以下数组)与关键字匹配。

[{
    "id": "13000001993",
    "title": "Most Popular",
    "answers": [{
      "id": "13000033122",
      "title": "Enrollment",
    }]
  },
  {
    "id": "13000000675",
    "title": "Support Questions",
    "answers": [{
      "id": "13000033122",
      "title": "Enrollment",
    }]
  }
]

https://codepen.io/anon/pen/VBzrYP

2 个答案:

答案 0 :(得分:3)

因为输入和输出数组不是一对一的,并且因为您需要返回一个更改的对象而不是原始对象,所以您可能应该使用reduce一口气:

const findTitle = 'Enrollment';
const input=[{"id":"13000001993","title":"Most Popular","answers":[{"id":"13000038079","title":"Price",},{"id":"13000033122","title":"Enrollment",}]},{"id":"13000000675","title":"Support Questions","answers":[{"id":"13000003646","title":"ADMIN Chat",},{"id":"13000033122","title":"Enrollment",}]},{"id":"130000005675","title":"Delivery","answers":[{"id":"13000003646","title":"Cost",}]}]

console.log(
  input.reduce((a, obj) => {
    const answers = obj.answers.filter(({ title }) => title === findTitle);
    if (answers.length > 0) a.push({ ...obj, answers });
    return a;
  }, [])
);

答案 1 :(得分:0)

您可以使用此功能在一系列问题中搜索answer

var data = [{"id":"13000001993","title":"Most Popular","answers":[{"id":"13000038079","title":"Price",},{"id":"13000033122","title":"Enrollment",}]},{"id":"13000000675","title":"Support Questions","answers":[{"id":"13000003646","title":"ADMIN Chat",},{"id":"13000033122","title":"Enrollment",}]},{"id":"130000005675","title":"Delivery","answers":[{"id":"13000003646","title":"Cost",}]}]

function searchByAnswer (search_key) {
  var serach_result = null;
  
  data.forEach((question) => {
    var finded_answer = null;

    if (question.answers && question.answers.length) {
      finded_answer = question.answers.find((answer) => {
        return answer.title.match(search_key) !== null;
      });
      
      if (finded_answer)
      	search_result = finded_answer;
    }
  });
  
  return search_result;
}