let myStr = "dress/cotton/black, dress/leather/red, dress/fabric, houses/restaurant/small, houses/school/big, person/james";
如何使用javascript将上述字符串转换为对象内的单独数组,例如:
{
dress = ["cotton","leather","black","red","fabric"];
houses = ["restaurant","school","small","big"];
person = ["james"];
}
您可以将字符串拆分为组,然后拆分为值。将第一个作为值的键,并将值连接到旧项目或新数组。然后将其分配给具有键的对象。
var string = "dress/cotton/black, dress/leather/red, dress/fabric, houses/restaurant/small, houses/school/big, person/james",
result = {};
string.split(', ').forEach(function (a) {
var values = a.split('/'),
key = values.shift();
result[key] = (result[key] || []).concat(values);
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句