Loop through a JSON object and return a key based on a specified value

loop through nested json object javascript
how to get key and value from json array object in javascript
javascript loop through object key, value pairs
get value from json object in javascript
get value from nested json object in javascript
iterate through json object java
javascript iterate object key, value
javascript loop through json object array

After getting results from my api call with postman I was trying to get the corresponding id of the value "KC Content Kind ID" in my success function below, but since its not an array I was wondering if each will work in jquery and how to go about it. I want to loop through this nested json object by going into the facet object and say if the name attribute is "KC Content Kind ID" then return the id for that corresponding name attribute

    "results": {
       "data": {
          "facets": {
              "60749428": {
                "id": 60749428,
                "name": "KC Content Content Kind"
              },
              "60750276": {
                "id": 60750276,
                "name": "KC Content Product Version"
              },
              "69107204": {
               "id": 69107204,
               "name": "KC Video Audience"
              },
              "69127027": {
               "id": 69127027,
               "name": "KC Content Kind ID"
             }
          }
       }
    }

This is my code and I am referring to the success function

function getAvailableKinds() {
$.ajax({
    url: csexe + "/api/v2/facets/" +getLocationId(),
    dataType: "json",
    type: "GET",
    beforeSend: function(xhr) {
        xhr.setRequestHeader ("OTCSticket", getAuthToken());
    },
    success: function(response) {
        var obj = response.results.data.facets;
        $.each(obj, function(item, value){
             if ( value.name == 'KC Content Kind ID') {
                 var idRequired = obj.id;
             }
        });
    },
    error: function(jqXHR, textStatus, errorThrown){
        alert("An error occurred... Look at the console");
        $("body").html('<p>status code: '+jqXHR.status+'</p><p>Error Thrown: ' + errorThrown + '</p><p>Response Text:</p><div>'+jqXHR.responseText + '</div>');
    }
});

You can use Object.keys() and then filter the results based on your test. For example:

let results = {"data": {"facets": {"60749428": {"id": 60749428,"name": "KC Content Content Kind"},"60750276": {"id": 60750276,"name": "KC Content Product Version"},"69107204": {"id": 69107204,"name": "KC Video Audience"},"69127027": {"id": 69127027,"name": "KC Content Kind ID"}}}}

let obj = results.data.facets;
let k = Object.keys(obj).filter(key => obj[key].name === "KC Content Kind ID")

// an array of all matches
console.log(k)

How to update a JSON file in Python, How do you remove a key value pair from a JSON object? This approach of looping through keys and values in an object can be used to perform more useful operations on the object, for instance the method could call a function passed in on each of the values. An example of this is in the foIn method in mout.js which iterates through the object keys and values calling the function passed in.

You get the id with Object.entries and find if you know that id is unique since Array.find would stop on the first match. This also would return the ID as well as the contents of the object.

const d = { "data": { "facets": { "60749428": { "id": 60749428, "name": "KC Content Content Kind" }, "60750276": { "id": 60750276, "name": "KC Content Product Version" }, "69107204": { "id": 69107204, "name": "KC Video Audience" }, "69127027": { "id": 69127027, "name": "KC Content Kind ID" } } } }

const r = Object.entries(d.data.facets).find(([k,v]) => v.name == "KC Content Kind ID")
console.log(r ? r[0] : undefined)

Ways to Loop Through Objects in JavaScript, How do I change the value of a JSON file? In this example I have created the one json array as string, and converted this string into JSON object using eval() function. Using for-each loop I got all the key value from jsonObj, and finally using that key I got the corresponding value. Finally I got the alert like this, Key: a value:10 Key: b value:20 Key: c value:30 Key: d value:50

If you're going to be performing that operation a lot you might find restructuring the data into an array easier to use.

const results = {"data":{"facets":{"60749428":{"id":60749428,"name":"KC Content Content Kind"},"60750276":{"id":60750276,"name":"KC Content Product Version"},"69107204":{"id":69107204,"name":"KC Video Audience"},"69127027":{"id":69127027,"name":"KC Content Kind ID"}}}};

// Get a list of the facet keys
const keys = Object.keys(results.data.facets);

// Pull those facet objects into an array
const arr = keys.reduce((acc, key) => acc.concat(results.data.facets[key]), []);
  
// Find the object that matches the required name, and return the id
const id = arr.find(el => el.name === 'KC Content Kind ID').id;
console.log(id);

JavaScript iterate through object keys and values (Example), methods such as forEach, map and reduce to retrieve the values of each key. If you’re working with JSON (JavaScript Object Notation) and either need to convert a JSON string to array or object and loop through it or vice-versa, take an array or object and convert it to a JSON string to return, both can be done in PHP or JavaScript.

You can loop over the facets object and determine if the last word points to a separate property other than name. If it does we return that property, if not, we return the name

Object.values(obj).map(o => {
  let prop = o.name.split(" ").pop().toLowerCase();
  return (prop in o) ? o[prop] : o.name;
});

let apiResult = {
  "results": {
    "data": {
      "facets": {
        "60749428": {
          "id": 60749428,
          "name": "KC Content Content Kind"
        },
        "60750276": {
          "id": 60750276,
          "name": "KC Content Product Version"
        },
        "69107204": {
          "id": 69107204,
          "name": "KC Video Audience"
        },
        "69127027": {
          "id": 69127027,
          "name": "KC Content Kind ID"
        }
      }
    }
  }
};

const loop = (obj) => Object.values(obj).map(o => {
    let prop = o.name.split(" ").pop().toLowerCase();
    return (prop in o) ? o[prop] : o.name;
  });
  
console.log(loop(apiResult.results.data.facets));

JSON Objects, hasOwnProperty(p) ) { result += p + " , " + obj[p] + "\n"; } } return result; } This approach of looping through keys and values in an object can be  JSON objects are surrounded by curly braces {}. JSON objects are written in key/value pairs. Keys must be strings, and values must be a valid JSON data type (string, number, object, array, boolean or null). Keys and values are separated by a colon. Each key/value pair is separated by a comma.

jQuery.each(), Loop through a JSON object and return a key based on a specified value. You get the id with Object.entries and find if you know that id is unique since Array.find would stop on the first match. This also would return the ID as well as the contents of the object. The listItemsSheet is a JSON Array and in this case contains only a single element. Your loop essentially is going to return the zeroth element which itself is a Json Object. So the loop is going to get called only once, and hence your code fails. The more appropriate way is to re-write this loop as shown below.

Help on how to loop through this json please - JavaScript, JSON objects are written in key/value pairs. Each key/value pair is separated by a comma. You can loop through object properties by using the for-in loop:  And in such a case where I had no control of the JSON data, how could I improve on my solution to iterate for selected user and iterate again through nested object's data? By the way, this is in context of studying JavaScript, not jQuery or any other library/framework.

Iterating Over and Reducing Data, In the case of an array, the callback is passed an array index and a If an object is used as the collection, the callback is passed a key-value pair We can break the $.each() loop at a particular iteration by making the callback function return  The key value gives us access to the current properties key ('key1’, 'key2’, 'key3’). The index provides us the index of the current item in the loop. This is simply the position of the item in the looped list (0, 1, 2).

Comments
  • So you would like the last word, whatever that is, to be the looked up property on the object who has a name that matches the rest of the text?
  • So I will like to say if get the 'id' of the 'name' attributes that matches 'KC Content Kind ID' in that result object
  • The problem is that your data is structured poorly. Facets should be an array of objects instead of an object with numbered properties. Then you can simply use array methods to locate the correct data. As it is, you will have to convert that data into an array before doing any operations on it, ie adding one step for each operation.