3

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>');
    }
});
3
  • 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? Commented Nov 29, 2018 at 17:46
  • So I will like to say if get the 'id' of the 'name' attributes that matches 'KC Content Kind ID' in that result object Commented Nov 29, 2018 at 17:48
  • 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. Commented Nov 29, 2018 at 18:23

4 Answers 4

1

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)

If you know there will be only one, find() will find the first match:

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).find(key => obj[key].name === "KC Content Kind ID")

// the first match
console.log(k)

Sign up to request clarification or add additional context in comments.

Comments

1

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)

If you return r[1] you would get the object with that key. r[0] returns your matched id only.

Comments

1

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);

Using that array you could write a general function to grab the information:

const arr = [{"id":60749428,"name":"KC Content Content Kind"},{"id":60750276,"name":"KC Content Product Version"},{"id":69107204,"name":"KC Video Audience"},{"id":69127027,"name":"KC Content Kind ID"}];

function findPropFromValue(arr, prop, key) {
  const [sKey, sVal] = [...Object.entries(prop)];
  return arr.find(el => el[sKey] === sVal)[key];
}

const id = findPropFromValue(arr, { name: 'KC Content Kind ID' }, 'id');
console.log(id);

const name = findPropFromValue(arr, { id: 69107204 }, 'name');
console.log(name);

Comments

0

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.