Array中的数组为单个数组

时间:2016-03-08 15:01:20

标签: javascript arrays

var value = [{
    "rowid": "one, two, three"
}, {
    "rowid": "four"
}]

var selected = value.map(function(varId) {
    return varId.rowid.toString();
});
console.log(selected);
console.log(selected.length);

我得到的输出是

["one, two, three", "four"]
2

但我期待

["one", "two", "three", "four"]
4

如何做到这一点?

4 个答案:

答案 0 :(得分:3)

使用String#split()Array#reduce()



var value = [{ "rowid": "one, two, three" }, { "rowid": "four" }],
    selected = value.reduce(function (r, a) {
        return r.concat(a.rowid.split(', '));
    }, []);

document.write('<pre>' + JSON.stringify(selected, 0, 4) + '</pre>');
&#13;
&#13;
&#13;

答案 1 :(得分:0)

如注释中所述,对象数组不是数组数组 无论如何尝试return varId.rowid.toString().split(',');

答案 2 :(得分:0)

试试这个:

var sel = value.map(function(varId) {
    var rowId = varId.rowid.toString();
    var splitted = rowId.split(",");    
    return splitted;
});
var arrayOfStrings = [].concat.apply([], sel);
for (int i = 0; i < arrayOfStrings.length; i++){
   arrayOfStrings[i] = arrayOfStrings[i].trim();
}

答案 3 :(得分:0)

您必须用逗号分隔您的第一个字符串(&#39;,&#39;), 然后展平多维数组。

var value = [{
    "rowid": "one, two, three"
}, {
    "rowid": "four"
}];

var selected = value.map(function(varId) {
    return varId.rowid.toString().split(', ');
});    
// [ [ 'one', 'two', 'three' ], [ 'four' ] ]
selected = [].concat.apply([], selected);
// [ 'one', 'two', 'three', 'four' ]
console.log(selected);
console.log(selected.length);