Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Taking 3 array elements and making them a single formatted string

I'm running an ajax request that returns JSON data:

{
"error":0,
"fleet":[
  {
     "fleet_uid":859805,
     "purpose":0,
     "ower":1,
     "time":520,
     "con_time":647,
     "from":[
        6,
        300,
        2
     ],
     "target":[
        6,
        300,
        6
     ],
     "start_user_id":20457507089,
     "target_user_id":20510481089,
     "start_planet_name":"Tweenis12",
     "target_planet_name":"P23808"
  },
  {
     "fleet_uid":859803,
     "purpose":0,
     "ower":1,
     "time":508,
     "con_time":647,
     "from":[
        6,
        300,
        2
     ],
     "target":[
        6,
        300,
        6
     ],
     "start_user_id":20457507089,
     "target_user_id":20510481089,
     "start_planet_name":"Tweenis12",
     "target_planet_name":"P23808"
  }
],
"count":2
}

I need to get only the target information inside the fleet property. Depending on the time, there might be no fleet entries and there might be 10+.

Inside the target property is 3 entries. I need to merge those 3 entries into a single string formatted like xx_xxx_xx

Being so unfamiliar with JS and jQuery, I'm not sure how to do this.


1 Answers

Try something like this,

var json = {"error":0,"fleet":[{"fleet_uid":859805,"purpose":0,"ower":1,"time":520,"con_time":647,"from":[6,300
,2],"target":[6,300,6],"start_user_id":20457507089,"target_user_id":20510481089,"start_planet_name":"Tweenis12"
,"target_planet_name":"P23808"},{"fleet_uid":859803,"purpose":0,"ower":1,"time":508,"con_time":647,"from"
:[6,300,2],"target":[6,300,6],"start_user_id":20457507089,"target_user_id":20510481089,"start_planet_name"
:"Tweenis12","target_planet_name":"P23808"}],"count":2};

var arr = [];
$.each(json.fleet, function(){
    var value = this.target;
    arr.push(value[0] + '_' + value[1] + '_' + value[2]);       
});
alert(arr);

demo in FIDDLE

like image 52
Lumi Lu Avatar answered Mar 28 '26 21:03

Lumi Lu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!