如何仅返回具有目标参数的对象?

时间:2018-08-08 13:40:28

标签: javascript arrays node.js object

例如,我有这个POST方法:

request_salaries(type)

type可以是redbluegreen

该函数返回此对象:

{
  data: [
    {
     id: 1,
     name: "Linda",
     type: "Red"
    },
    {
      id: 2,
      name: "Mark",
      type: "Green
    },
    {
      id: 3,
      name: "Susan",
      type: "Blue"
    }
  ]
}

现在,我只需要返回在request_salaries(type)中传递的那部分数据。

例如,如果我请求request_salaries(红色)

它应该返回:

{
  data: [
    {
     id: 1,
     name: "Linda",
     type: "Red"
    },
  ]
}

这如何实现?

谢谢。

4 个答案:

答案 0 :(得分:4)

只需过滤出适当的值:

const response = { /* your data */ };
const type = 'red';

const filteredResponse = response.data.filter(item => item.type === type)

答案 1 :(得分:1)

尝试过滤您的退货

request_salaries(type){

// fetch data and set it in array_salaries


return array_salaries.filter(salary => salary.type == type)



}

答案 2 :(得分:1)

您可以使用Array.find()

var obj = {
  data: [
    {
     id: 1,
     name: "Linda",
     type: "Red"
    },
    {
      id: 2,
      name: "Mark",
      type: "Green"
    },
    {
      id: 3,
      name: "Susan",
      type: "Blue"
    }
  ]
};
var val = 'Red';
var res = obj.data.find(({type}) => type===val);
console.log(res);

答案 3 :(得分:1)

您可以使用.find()方法

var type = 'red';

const result = response.data.find(function(item) {
    return item.type === type;
});

使用箭头功能:

const result = response.data.find( item => item.type === type );