angularjs - javascript - 将对象值从数组转换为字符串

时间:2016-07-25 20:39:56

标签: javascript arrays json string object

我在js中遇到了对象,json等的一些问题。如果有人可以帮助我,那将是惊人的! :)

我有一个对象,我无法改变,就像这样:

{
  "page": [
    "POST",
    "DELETE"
  ],
  "news": [
    "PUT"
  ]
}

我想转换成这样:

{
  "page": "POST, DELETE",
  "news": "PUT"
}

所以我希望对象值(数组)是字符串,我也尝试过toString(),String(),JSON.stringify和其他来自互联网的方法,(也许我没有做对)但没有工作对我来说,我对处理这些类型的数据有点新意,所以如果有人可以帮助我,TKS !! :D

修改

在我得到这种结构的情况下:

{
  "page": {
    "POST": [
      "POST"
    ],
    "PUT": 122
  },
  "news": {
    "PUT": [
      "PUT"
    ]
  }
}

我如何转换为:

{
  "page": "POST, PUT:122",
  "news": "PUT"
}

5 个答案:

答案 0 :(得分:0)

假设您的对象始终将数组作为属性值,您可以使用如下所示的javascript执行此操作

 var obj = {
     "page": [
         "POST",
         "DELETE"
     ],
     "news": [
         "PUT"
     ]
 };


 for (var o in obj) {
     if (obj.hasOwnProperty(o)) {
         obj[o] = obj[o].join(", ");
     }
 }

 console.log(obj);

答案 1 :(得分:0)

好的,您可以使用var str = array.join(stringThatIsSupposedToBeInbetweenTheValues);将数组的所有值添加到字符串中(连接它们)。所以在你的情况下,array.join(', ');。请注意,此字符串仅放在单个值之间,而不是它们周围(在结果的开头或结尾)。更多信息here

我希望有所帮助!

答案 2 :(得分:0)

有很多方法可以做到这一点。只需要遍历对象并将数组设置为字符串。



var obj = {
  "page": [
    "POST",
    "DELETE"
  ],
  "news": [
    "PUT"
  ]
};

Object.keys(obj).reduce( function (o, key) {  
    o[key] = o[key].join(", ");
    return o;
}, obj);

console.log(obj);




使用forEach可能有意义,但减少工作。

答案 3 :(得分:0)

你可以这样做;

var o = {
  "page": [
    "POST",
    "DELETE"
  ],
  "news": [
    "PUT"
  ]
},
    p = Object.keys(o).reduce((p,k) => (p[k] = o[k]+"",p),{});
console.log(p);

答案 4 :(得分:0)

如果您想修改初始对象 - 使用select * into #control from tablename declare @acum as int declare @code as char(3) declare @id as char(1) declare @id2 as int select @acum=0 while exists (select* from #control) begin select @code = (select top 1 code from #control order by id) select @id = (select top 1 id from #control order by id) select @id2 =count(id) from #control where id in (select id from tablename where id = @id and code <> @code) if @id2=0 begin select @acum = @acum+1 end delete #control where id = @id --and code = @code end drop table #control print @acum Object.keys函数就足够了:

&#13;
&#13;
Array.forEach
&#13;
&#13;
&#13;

另一个复杂案例的

附加解决方案

&#13;
&#13;
var obj = {
  "page": [
    "POST",
    "DELETE"
  ],
  "news": [
    "PUT"
  ]
};

Object.keys(obj).forEach(function(k) {
  obj[k] = obj[k].join(",");
});

console.log(JSON.stringify(obj, 0, 4));
&#13;
&#13;
&#13;