返回没有方括号的json对象

时间:2021-04-08 21:42:33

I have a function which returns an object of form: [{"key":"name","value":"ali","key":"age","value":"56"}] when called as given below. How can I have it return same kind of object but without the square brackets?

我有一个函数返回一个形式的对象:[{“key”:“name”,“value”:“ali”,“key”:“age”,“value”:“56”}]当被调用时下面。我怎么能让它返回相同类型的对象但没有方括号?

setProperties('{"name":"ali","age":"56"}');

function setProperties(str) {
    var properties = [];
    var json = jQuery.parseJSON(str);
    for (property in json) {
      properties.push({
        key: property,
        value: json[property]});
    }
    return properties;
}

2 个解决方案

#1


6  

return properties[0]; // returns the first element of the list instead of the whole list

#2


5  

The square brackets indicate an Array literal, so if you just select the first element of the Array: [{"name":"ali","age":"56","height":"xyz"}][0] it returns the Object you want.

方括号表示一个数组文字,所以如果你只选择数组的第一个元素:[{“name”:“ali”,“age”:“56”,“height”:“xyz”}] [0]它返回你想要的对象。

#1


6  

return properties[0]; // returns the first element of the list instead of the whole list

#2


5  

The square brackets indicate an Array literal, so if you just select the first element of the Array: [{"name":"ali","age":"56","height":"xyz"}][0] it returns the Object you want.

方括号表示一个数组文字,所以如果你只选择数组的第一个元素:[{“name”:“ali”,“age”:“56”,“height”:“xyz”}] [0]它返回你想要的对象。