JavaScript过滤器数组结果

时间:2018-07-19 16:41:31

标签: javascript arrays filter

我正在尝试对数组进行JavaScript过滤,但是以某种方式在需要分隔时返回一个数组(0个第一数据1个第二数据),以便我可以轻松地在另一个循环中处理它。我希望以下内容有意义。预先感谢您的任何帮助。

JSON输入

[
    {
        "id": 1,
        "title": "Ford F-150",
        "type": "truck"
    },
    {
        "id": 2,
        "title": "BMW 4 series",
        "type": "car"
    },
    {
        "id": 3,
        "title": "Triumph Scrambler",
        "type": "motorbike"
    },
    {
        "id": 4,
        "title": "Audi A3",
        "type": "car"
    }
]

INTO数据过滤掉了

function filterByProperty(array, prop, value){
    var filtered = [];

    for (var i = 0; i < array.length; i++) {
        var obj = array[i];

        for (var key in obj) {

            if (typeof(obj[key] === "object")) {
                var item = obj[key];

                if(obj[prop] == value){
                    filtered.push(item);
                }
            } else {
              console.log("not object");
            }
        }
    }    

    return filtered;
}


var filtereddata = filterByProperty(data, "type", "car");
console.log(filtereddata);

运行此命令时,我只会看到一个数组而不是两个?

8 个答案:

答案 0 :(得分:1)

作为其他答案的替代方法,我对您的代码进行了些许更改以使其起作用。无需遍历每个“车辆”对象中的每个键,它只是在第一个for循环中检查等于prop的每个车辆value

此处提供代码:

var data = [
        {
            "id": 1,
            "title": "Ford F-150",
            "type": "truck"
        },
        {
            "id": 2,
            "title": "BMW 4 series",
            "type": "car"
        },
        {
             "id": 3,
             "title": "Triumph Scrambler",
             "type": "motorbike"
        },
        {
            "id": 4,
            "title": "Audi A3",
            "type": "car"
        }
    ];    

    function filterByProperty(array, prop, value){
        var filtered = [];
        for(var i = 0; i < array.length; i++){
            var obj = array[i];
            if(obj[prop] == value)
                filtered.push(obj);
            else{
                console.log("not a " + value);
            }
        }    
        return filtered;
    }


    var filtereddata = filterByProperty(data, "type", "car");

    console.log(filtereddata);

希望这对某人有帮助!

答案 1 :(得分:1)

您只将值推入一个数组并返回一个数组。这就是为什么您只能得到一个数组的原因...

像这样尝试:

function filterProp(data, prop){
    return data.filter(el => {
        return el.type === prop
    })
}

然后只需使用:

console.log(filterProp(data, 'car'))

或者如果您需要指定密钥:

function filterProp(data, key, prop){
    return data.filter(el => {
        return el[key] === prop
    })
}

console.log(filterProp(data, 'title', 'BMW'))

答案 2 :(得分:1)

在ES6中,数组具有内置方法.filter来过滤项目。 它对Array.prototype.filter()

的糖语法

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

const data = [
    {
        "id": 1,
        "title": "Ford F-150",
        "type": "truck"
    },
    {
        "id": 2,
        "title": "BMW 4 series",
        "type": "car"
    },
    {
        "id": 3,
        "title": "Triumph Scrambler",
        "type": "motorbike"
    },
    {
        "id": 4,
        "title": "Audi A3",
        "type": "car"
    }
];

const filter = (d, prop, value) => d.filter((obj) => obj[prop] === value);
const filtereddata = filter(data, "type", "car");

console.log(filtereddata);

答案 3 :(得分:1)

首先,有关typeof的注释是一个关键字,而不是一个函数。

像函数一样使用它意味着它首先评估obj[key] == "object"
由于计算结果为false,因此typeof返回boolean,因为typeof falseboolean

boolean是一个truthy值,因此您永远不会点击else子句。

也就是说,您可以通过以下方式修复功能:

  • 消除typeof支票。
  • 添加另一项检查,以确保key与传入的prop匹配。
  • 并将obj推入数组以返回。

function filterByProperty(array, prop, value) {
    var filtered = [];
    for (var i = 0; i < array.length; i++) {
        var obj = array[i];
        for (var key in obj) {
            if (key === prop && obj[prop] == value) {
                filtered.push(obj);
            }
        }

    }

    return filtered;

}


const data = [{
        "id": 1,
        "title": "Ford F-150",
        "type": "truck"
    },
    {
        "id": 2,
        "title": "BMW 4 series",
        "type": "car"
    },
    {
        "id": 3,
        "title": "Triumph Scrambler",
        "type": "motorbike"
    },
    {
        "id": 4,
        "title": "Audi A3",
        "type": "car"
    }
];

var filtereddata = filterByProperty(data, "type", "car");

console.log(filtereddata);

或者,您可以改用Array.filter

const filterByProperty = (arr, prop, value) => arr.filter(o => o[prop] && o[prop] === value);

const data = [{
        "id": 1,
        "title": "Ford F-150",
        "type": "truck"
    },
    {
        "id": 2,
        "title": "BMW 4 series",
        "type": "car"
    },
    {
        "id": 3,
        "title": "Triumph Scrambler",
        "type": "motorbike"
    },
    {
        "id": 4,
        "title": "Audi A3",
        "type": "car"
    }
];

const filtered = filterByProperty(data, 'type', 'car');
console.log(filtered);

答案 4 :(得分:0)

您可以使用Array.filter按属性值进行过滤

var data = [
      {
        "id": 1,
        "title": "Ford F-150",
        "type": "truck",
        "date": "2017-12-23"
      },
      {
        "id": 2,
        "title": "BMW 4 series",
        "type": "car",
        "date": "2017-12-22"
      },
      {
        "id": 3,
        "title": "Triumph Scrambler",
        "type": "motorbike",
        "date": "2017-12-21"
      },
      {
        "id": 4,
        "title": "Audi A3",
        "type": "car",
        "date": "2017-12-20"
      }
];
        
      function filterByProperty(array, prop, value){
          return newArray = array.filter(function (el) {
            return el[prop] == value;
          });
      }
      function compare(a,b) {
        if (new Date(a.date) < new Date(b.date))
          return -1;
        if (new Date(a.date) > new Date(b.date))
          return 1;
        return 0;
      }

      var filtereddata = filterByProperty(data, "type", "car");
      console.log(filtereddata.sort(compare));

答案 5 :(得分:0)

尝试使用Array.filter(callback)

function filterByProperty(array, prop, value) {
    var filtered = array.filter(item => {
      item[prop] === value;
    }
    return filtered;
}

var filtereddata = filterByProperty(data, "type", "car");

console.log(filtereddata);

答案 6 :(得分:0)

您可以使用此功能:

var data =[
        {
        "id": 1,
        "title": "Ford F-150",
        "type": "truck"
        },
        {
        "id": 2,
        "title": "BMW 4 series",
        "type": "car"
        },
        {
        "id": 3,
        "title": "Triumph Scrambler",
        "type": "motorbike"
        },
        {
        "id": 4,
        "title": "Audi A3",
        "type": "car"
        }
        ]
        
        filterByProperty(data, 'type', 'car');
        function filterByProperty(data, prop, value){
        	for(i=0; i<data.length; i++){
          	if(data[i][prop]==value){
            	console.log(data[i]);
            }
          }
        }

答案 7 :(得分:0)

正如manavM所说,为此创建了内部array.filter类。 原始阵列保持不变。 第二个数组filteredArr包含对return语句返回true的所有项目。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

https://www.w3schools.com/jsref/jsref_filter.asp

function filterByProperty(arr, prop, val) {
    const filteredArr = arr.filter(function (v) {
      return typeof v === 'object' && v[prop] == val;
    });
    console.log(arr);
    console.log(filteredArr);
};
filterByProperty([{
    "id": 1,
    "title": "Ford F-150",
    "type": "truck"
    },{
    "id": 2,
    "title": "BMW 4 series",
    "type": "car"
    },{
    "id": 3,
    "title": "Triumph Scrambler",
    "type": "motorbike"
    },{
    "id": 4,
    "title": "Audi A3",
    "type": "car"
    }], "type", "car");