将文本附加到json数组中的值

时间:2013-09-13 11:41:06

标签: javascript jquery json

如何仅将文本附加到数组的第一个值并将数组发送回服务器。这是我从服务器获得的响应

[{
    "12": [ "12", "1", "2", "3" ]
}, {
    "13": [ "13", "1", "2", "3" ]
}, {
    "14": [ "14", "1", "2", "3" ]
}, {
    "15": [ "15", "1", "2", "3" ]
}]

我希望我的数组现在是这样的,这样我就可以将这个数组传递给我的数据表了。

var object = [{
    12: ["12 hrs", "1", "2", "3"]
}, {
    13: ["13 hrs", "1", "2", "3"]
}, {
    14: ["14 hrs", "1", "2", "3"]
}, {
    15: ["15 hrs", "1", "2", "3"]
}]

如何将hrs附加到第一个值?

2 个答案:

答案 0 :(得分:0)

我将问题中的object修改为 -

var objectArray = [{"12" : ["12", "1", "2", "3"]}, {"13" : ["13", "1", "2", "3"]},{"14" : ["14", "1", "2", "3"]},{"15" : ["15", "1", "2", "3"]}]

这是你如何循环objectArray并改变你想要的方式 -

for(var i=0;i<objectArray.length;i++)
{
    for(var key in objectArray[i])
    {
        objectArray[i][key][0]+=" hrs";
        break;
    }
}

console.log(objectArray)

答案 1 :(得分:0)

这是一种简单的方法......

// Parse the string response from the server into an object
var obj = JSON.parse(serverResponse);
// loop through the object, knowing that it's nested in the first index of an array "obj[0]"
for(id in obj[0]){
    // obj->arrayIndex->objectProperty->arrayIndex append " hrs"
    obj[0][id][0] += " hrs";
}
// to return this to the server, apply JSON.stringify(obj)