取3个数组元素并使它们成为单个格式化的字符串

时间:2015-04-23 00:51:03

标签: javascript jquery

我正在运行一个返回JSON数据的ajax请求:

{
"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
}

我只需要获取fleet属性中的目标信息。根据时间的不同,可能没有车队参赛作品,可能会有10 +。

目标属性内有3个条目。我需要将这3个条目合并为一个格式为xx_xxx_xx

的字符串

由于不熟悉JS和jQuery,我不知道该怎么做。

3 个答案:

答案 0 :(得分:2)

尝试这样的事情,

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);
<{3}}

中的

演示

答案 1 :(得分:0)

如果数据是对响应的引用,那么

if(data.target && data.target.length){
    data.target = target.join('_');        
}

如果你想让X替换字符,那么

var target = data.target;
if(target && target.length){
    target = target.join('_');
    target = target.replace(/\d/g, 'x')      
}
data.target = target;

答案 2 :(得分:0)

在这里可视化你的json - http://jsonmate.com/permalink/553846afaa522bae3683edc8
这是我第一次想出在Javascript中访问json对象的点符号。在下面的代码中,我将通过可视化的路径跟踪到目标对象。舰队是阵列。目标也是阵列。

var 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};

var targets = []; //array of targets in fleets

for (var i = 0; i < data.fleet.length; i++)  {
  var a = data.fleet[i].target[0];
  var b = data.fleet[i].target[1];
  var c = data.fleet[i].target[2];
  var target = a + "_" + b + "_" + c;
  targets.push(target);
}

alert(targets);