所以我有一个类似的JS对象:
let object =
{
"key1":"value1",
"key2":"value2",
"key3":"value3"
}
对于迭代,我使用以下内容:for (let i = 0; i < Object.keys(object).length; i++)
现在,我想做的基本上是:
let value;
if (data === undefined || data === "") {
value = []
} else if (data.includes(",")) {
value = data.split(",")
} else if (data.includes(".")) {
value = data.split(".")
} else {
value = data.split(" ");
}
所以,我尝试了Object.values(entries_array).split(",")
,但split不是Object方法。所以,如果你能帮我找到一个解决方案。提前谢谢。
编辑:对不起,我会努力描述更多我想要实现的目标。我想通过代码,获得用相同键更改但值被拆分的对象变量。
例如,如果值有逗号,我想拆分该值。如果没有,什么也不做。
现在,我有这个:
let object =
{
"key1":"value1",
"key2":"value2",
"key3":"value3"
}
const entries = Object.entries(object);
const entries_array = Object.fromEntries(entries)
let data_val;
for (let i = 0; i < Object.keys(entries_array).length; i++) {
Object.values(entries_array).forEach(val => {
if (val === undefined || val === "") {
data_val = []
} else if (val.includes(",")) {
data_val = val.split(",")
} else if (val.includes(".")) {
data_val = val.split(".")
} else {
data_val = val.split(" ");
}
});
}
return entries_array;
function reassignValueAsArray(obj, [key, value]) {
obj[key] = value.split(/s*[., ]s*/);
return obj;
}
function reassignKeyValuesAsArray(obj) {
return Object
.entries(obj)
.reduce(reassignValueAsArray, obj);
}
const sampleObject = {
"key1": "value1,value1b",
"key2": "value2.value2b",
"key3": "value3 value3b",
"key4": "value4.value4b,value4c value4d",
"key5": "value5-value5b-value5c-value5d",
};
reassignKeyValuesAsArray(sampleObject);
console.log(sampleObject);
.as-console-wrapper { min-height: 100%!important; top: 0; }