阵列中的数组到单个数组

Array within an Array to single Array

本文关键字:数组 单个 阵列      更新时间:2023-09-26
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

如何做到这一点?

使用 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>');

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

你必须用逗号(', ')拆分你的第一个字符串,然后展平多维数组。

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);

试试这个:

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();
}