locked
How to Filter JSON Array? RRS feed

  • Question

  • User-930371450 posted


    var users=
    [
    {DepartmentID: 13, NAME: "Apple", Score:100},
    {DepartmentID: 108, NAME: "Samsung", Score:90},
    {DepartmentID: 162, NAME: "Sony", Score:80},
    {DepartmentID: 1194, NAME: "HTC", Score:70},
    {DepartmentID: 1346, NAME: "Nokia", Score:100}
    ];

    var objPrintUsersScore = $.grep(users, function (v) {
    return v.DepartmentID ==13;
    });


    Result is getting like undefined[object Object]

    I need like this [{DepartmentID: 13, NAME: "Apple", Score:100}]

    Thursday, January 23, 2020 12:50 PM

All replies

  • User753101303 posted

    Hi,

    Be explicit about what you are doing next. It should be an [object Object] and the following code works fine. For now I suspect you are looking as well at some other variable not shown in this code and which is the one that is really undefined...

    var users=
    [ {DepartmentID: 13, NAME: "Apple", Score:100}, {DepartmentID: 108, NAME: "Samsung", Score:90}, {DepartmentID: 162, NAME: "Sony", Score:80}, {DepartmentID: 1194, NAME: "HTC", Score:70}, {DepartmentID: 1346, NAME: "Nokia", Score:100} ]; var objPrintUsersScore = $.grep(users, function (v) { return v.DepartmentID ==13; }); alert(objPrintUsersScore[0].DepartmentID); // shows 13 as expected, be explicit about what you show to get your undefined value

    Edit: and alert(JSON.stringify(objPrintUsersScore)); would show the expected JSON string. We likely miss what you are doing next...

    Thursday, January 23, 2020 1:05 PM
  • User475983607 posted

    I would use filter().

    const result = users.filter(item => item.DepartmentID == 13);

    Or

    const result = users.filter(function(item){
    	return item.DepartmentID == 13
    });

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

    Thursday, January 23, 2020 1:19 PM