skip to Main Content

I Used AJAX request to availability of Shop title of our system. In there i used use api and it response like this

"[{"count":2,"seller_id_1":"1207","title_1":"PRIMA CEYLON PVT
LTD","url_1":"prima-ceylon-pvt-ltd","seller_id_2":"6509","title_2":"Prima
Management Services (Pvt)
Ltd","url_2":"prima-management-services-pvt-ltd"}]"

data retrieve using data response object’s 0th element.

if response get 10 results (I means count of my response) that results generate 10 key value for title , url and seller_id .

that result following like this

title_1 :
url_1
seller_id_1 :

title_2 :
url_2
seller_id_2 :

when data catching i have to hard coded those things . So there is any mechanism to increment key value instead of hard coded.

I need to fetch value in as follow

json[0].title_1  

json[0].url_1

json[0].title_2  

json[0].url_2

Thank you

2

Answers


  1. Chosen as BEST ANSWER

    var json = JSON.parse(
      '[{"count":2,"seller_id_1":"1207","title_1":"PRIMA CEYLON PVTLTD","url_1":"prima-ceylon-pvt-ltd","seller_id_2":"6509","title_2":"Prima Management Services (Pvt)Ltd","url_2":"prima-management-services-pvt-ltd"}]'
    );
    
    var i = 1;
    var response_count = json[0].count;
    
      for (i = 1; i <= response_count; i++) {
        
        console.log(json[0]['url_' + i]);
    
      }


  2. You can build an object with values as array of values of the variables.

    result[title][0] –> will be title_1
    result[title][1] –>
    will be title_2

    Similarly other values

    const [data] = JSON.parse(
      '[{"count":2,"seller_id_1":"1207","title_1":"PRIMA CEYLON PVTLTD","url_1":"prima-ceylon-pvt-ltd","seller_id_2":"6509","title_2":"Prima Management Services (Pvt)Ltd","url_2":"prima-management-services-pvt-ltd"}]'
    );
    
    
    const result = {
      'seller_id': [], 'title': [], 'url': []
    };
    
    for (let i = 1; i <= data.count; i++) {
      Object.keys(result).forEach(key => result[key].push(data[`${key}_${i}`]));
    }
    
    console.log(result);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search