将Transform和Instance Variable转换为对象的JavaScript数组

Transform and Instance Variable into a JavaScript array of objects

本文关键字:对象 JavaScript 数组 转换 Transform Instance Variable      更新时间:2023-09-26

如何将此实例变量转换为对象的JavaScript数组

我知道我和有关系

但当我尝试的时候,它完全错了。。

这就是我得到的:(报价)

@updates = [
  "{'24548_0_load_results': ['1630609','2015-04-07 13:51:03 UTC','7 minutes']}", 
  "{'24548_0_load_results': ['1630610','2015-04-07 13:51:03 UTC','7 minutes']}"
]

创建了上面的这个:

  @updates = []
  records.each do |r|
    updates << "{ '" + t.search_table_id.to_s + "': " + Search.load_post_result(r, s).to_s + " }"
  end

这就是我需要它的方式:

var obj1 = {
    "loads": [
        {'24547_1428357240_load_results' : ['1630607','2015-04-06 18:35:46 UTC','8 minutes']},
        {'24547_1428357240_load_results' : ['1630606','2015-04-06 18:35:47 UTC','8 minutes']}
    ]
};

这是我正在字符串中的脚本,用于通过运行此对象数组

$.each(obj1["loads"], function(k, v){
    $.each(v, function(key, value) {
        alert(key + ": " + value);
    })
});

编辑:这就是我现在拥有的

var obj1 = {
    "loads": []
};
for (string in <%= @updates1 %>){
    obj1["loads"].push(JSON.parse(string.replace(/'/g,''"')));
}
$.each(obj1["loads"], function(k, v){
    $.each(v, function(key, value) {
        alert(key + ": " + value);
    })
});

回复中是这样的:

var obj1 = {
    "loads": []
};
for (string in [&quot;{ '24549_1428420484_load_results': ['1630610','2015-04-07 14:44:37 UTC','44 minutes','Springfield, MO','Dallas, TX','04/07','04/07','Full','Flatbed or Van or Reefer','','53','0.00'] }&quot;, &quot;{ '24549_1428420484_load_results': ['1630609','2015-04-07 13:51:03 UTC','about 2 hours','Springfield, MO','Dallas, TX','04/10','04/11','Full','Flatbed or Van or Reefer','','53','0.00'] }&quot;]){
    obj1["loads"].push(JSON.parse(string.replace(/'/g,''"')));
}
$.each(obj1["loads"], function(k, v){
    $.each(v, function(key, value) {
        alert(key + ": " + value);
    })
})

您可以用如下javascript完成:

    JSON.parse("YourString".replace(/'/g,''"'))

这里有一把小提琴要示范。

https://jsfiddle.net/ab19ha1o/

您需要替换单引号来正确解析JSON,所以这是一种快速而肮脏的方法:)

编辑:这是JSON分析的SO线程:jQuery.parseJSON单引号与双引号

您只需要对每个字符串进行迭代就可以得到对象。

编辑:完整的传输看起来像这样:

    for (string in updates){
      obj1["loads"].push(JSON.parse(string.replace(/'/g,''"')));
    }