Home > Enterprise >  How can I filter data in json file?
How can I filter data in json file?

Time:03-01

I've a external JSON file like this:

{"colors":[{
        "color": "red",
        "value": "#f00"
    },
    {
        "color": "green",
        "value": "#0f0"
    },
    {
        "color": "blue",
        "value": "#00f"
    }]}

I want to filter data in order to obtain the name giving the value. This is my code:

$.ajax({
        url: "./data.json",
        dataType: "json",
        type: "get",
        cache: false,
        success: function (json){
            $(json.colors).each(function(i,data){

                let key="value";
                let value="#00f";
                let result= data.filter(d=>d[key]==value);
                console.log(result)

            
            });
        }
    })

Obv it doesn't work. How can I resolve this? Thanks in advance to who will help me.

const json = `{"colors":[{
  "color": "red",
  "value": "#f00"
},
{
  "color": "green",
  "value": "#0f0"
},
{
  "color": "blue",
  "value": "#00f"
}]}`;

function fakeAjax(options) {
    setTimeout(() => {
        options.success(JSON.parse(json));
    }, 800);
}

fakeAjax({
    url: "./data.json",
    dataType: "json",
    type: "get",
    cache: false,
    success: function (json){
        $(json.colors).each(function(i,data){
            let key="value";
            let value="#00f";
            let result= data.filter(d=>d[key]==value);
            console.log(result)


        });
    }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

CodePudding user response:

The problem is that in your each callback, data is an object (each of the objects from colors), but you're trying to treat it like an array.

You seem to want to find the color with value === "#00f". If so, you don't need that many layers of loops, you've already gone into the object to get the colors array, just use filter on it directly:

success: function (obj){ // chnaged name, it's not JSON
    const key = "value";
    const value = "#00f";
    const result = obj.colors.filter(color => color[key] === value);
    console.log(result);
}

Updated snippet:

const json = `{"colors":[{
  "color": "red",
  "value": "#f00"
},
{
  "color": "green",
  "value": "#0f0"
},
{
  "color": "blue",
  "value": "#00f"
}]}`;

function fakeAjax(options) {
    setTimeout(() => {
        options.success(JSON.parse(json));
    }, 100);
}

fakeAjax({
    url: "./data.json",
    dataType: "json",
    type: "get",
    cache: false,
    success: function (obj){ // chnaged name, it's not JSON
        let key="value";
        let value="#00f";
        const result = obj.colors.filter(color => color[key] === value);
        console.log(result);
    }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Or if you wanted just the first color object, not all matching color objects, you'd use find:

success: function (obj){ // chnaged name, it's not JSON
    const key = "value";
    const value = "#00f";
    const result = obj.colors.find(color => color[key] === value);
    console.log(result);
}

Updated snippet:

const json = `{"colors":[{
  "color": "red",
  "value": "#f00"
},
{
  "color": "green",
  "value": "#0f0"
},
{
  "color": "blue",
  "value": "#00f"
}]}`;

function fakeAjax(options) {
    setTimeout(() => {
        options.success(JSON.parse(json));
    }, 100);
}

fakeAjax({
    url: "./data.json",
    dataType: "json",
    type: "get",
    cache: false,
    success: function (obj){ // chnaged name, it's not JSON
        let key="value";
        let value="#00f";
        const result = obj.colors.find(color => color[key] === value);
        console.log(result);
    }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

CodePudding user response:

As data is an object, .filter method will not work as it works only with arrays.

Working Demo in jQuery :

// This is what you're receiving in your `success` callback
const json = {
    colors: [{
      color: "red",
      value: "#f00"
    },{
      color: "green",
      value: "#0f0"
    },{
      color: "blue",
      value: "#00f"
    }]
};

let key = "value";
let value = "#00f";

const result = $.makeArray(json.colors).filter((data) => data[key] === value);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

CodePudding user response:

If you are getting data from ajax then check below code to filter the data.

$.ajax({
url: "./data.json",
dataType: "json",
type: "get",
cache: false,
success: function (json){
    $(json.colors).each(function(i,data){
        let key="value";
        let value="#00f";           
        let result = data.filter(function (elem) {return elem[key] === value})[0];
        console.log(result)

    
    });
}

})

  • Related