从多维数组创建逗号分隔的字符串

时间:2014-10-22 12:08:46

标签: javascript csv multidimensional-array

我有一个多维数组,如下所示:

[
    Object {href="http://www.somepath.com/car4.png", title="Wheel"},
    Object {href="http://www.somepath.com/car.png", title="Top"},
    Object {href="http://www.somepath.com/car1.png", title="Side"},
    Object {href="http://www.somepath.com/car5.png", title="Saddle"},
    Object {href="http://www.somepath.com/car6.png", title="Front"}
]

我想循环遍历此对象并检索两个逗号分隔的字符串,一个用于所有href,一个用于所有标题。所以我要追求的是:

hrefs = "'http://www.somepath.com/car4.png', 'http://www.somepath.com/car.png', 'http://www.somepath.com/car1.png', 'http://www.somepath.com/car5.png', 'http://www.somepath.com/car6.png'";
titles = "'Wheel', 'Top', 'Side', 'Saddle', 'Front'";

虽然看起来很容易但我缺乏知识,似乎无法找到具体的答案。

4 个答案:

答案 0 :(得分:4)

一个简单的函数,使用map将值放入数组中,然后将它们连接起来。

function createString(arr, key) {
  return arr.map(function (obj) {
    return "'" + obj[key] + "'";
  }).join(', ');
}

// pass in the array and the key the values of which
// you want to 'stringify'
var hrefs = createString(arr, 'href');
var titles = createString(arr, 'title');

DEMO

答案 1 :(得分:0)

你可以这样做:

var hrefs = [],
    titles = [];

data.forEach(function(obj) {
    hrefs.push("'" + obj.href + "'");
    titles.push("'" + obj.title + "'");
});

hrefs = hrefs.join(', ');
titles = titles.join(', ');

答案 2 :(得分:0)

var data = [
    {href:"http://www.somepath.com/car4.png", title:"Wheel"},
    {href:"http://www.somepath.com/car.png", title:"Top"},
    {href:"http://www.somepath.com/car1.png", title:"Side"},
    {href:"http://www.somepath.com/car5.png", title:"Saddle"},
    {href:"http://www.somepath.com/car6.png", title:"Front"}
],
href = [],
title = [],
dataL = data.length;

for ( i = 0; i < dataL; i++ ){
   href.push ( data[i]['href'] );
   title.push ( data[i]['title'] );
}

href = href.join(",");
title = title.join(",");

答案 3 :(得分:0)

基于另一个数组内容生成数组的规范函数是map。然后,您可以将其与join组合以生成所需的字符串:

var hrefs = data.map(function(d) { return "'" + d.href + "'" }).join(', ');
var titles = data.map(function(d) { return "'" d.title + "'" }).join(', ');

请注意,如果字段中有任何单引号,则无法生成有效的CSV。解决方案是提供更严格的引用功能。遵循通常的惯例,字符串中的引号应该加倍:

function enquote(v) {
    return "'" + v.replace(/'/g, "''") + "'";
}

用法:

var titles = data.map(function(d) { return enquote(d.title) }).join(', ');