我正在使用來自 x<input>欄位的用戶輸入創建和填充一個物件。到目前為止,我已經成功地創建了物件并使用用戶輸入填充它。但是,我堅持下一步。
我想抓取和修改用戶輸入,并使用逗號將其分隔為嵌套屬性進行拆分。
這可能是一項簡單的任務,但我想不出一個可行的解決方案。我怎樣才能做到這一點?(不確定我對自己的解釋有多好,所以我發布了一個所需輸出的示例)
html:(可能比那些 2x2 更多的輸入欄位)
<input type="text" name="test_1.Title" class="tests">
<input type="text" name="test_1.String" class="tests">
<input type="text" name="test_2.Title" class="tests">
<input type="text" name="test_2.String" class="tests">
function objectMaker() {
function objectSubs(obj, keys, value) {
let key = keys.shift()
if (keys.length) {
obj[key] = obj[key] || {}
objectSubs(obj[key], keys, value)
return
}
obj[key] = value
}
function grabTestData(){
var inputs = document.getElementsByClassName('tests');
var testObject = {}
Object.keys(inputs).forEach(i => {
let inputName = inputs[i].getAttribute('name');
objectSubs(testObject, inputName.split('.'), inputs[i].value)
})
}
grabTestData()
}
當前物件:
var testObject = {
tests1: {
title: "random title",
string: "somestring, other string, and anotherString",
},
tests2: {
title: "other random title",
string: "thisString, thatString, a String there",
},
}
想要的物件:
var testObject = {
tests1: {
title: "random title",
string: {
substring1: "somestring",
substring2: "other string",
substring3: "and anotherString",
},
},
tests2: {
title: "other random title",
string: {
substring1: "thisString",
substring2: "thatString",
},
},
}
uj5u.com熱心網友回復:
如果您想創建一個函式將物件轉換為您想要的格式:
function splitStrings(obj) {
Object.values(obj).forEach(val => val.string = Object.fromEntries(val.string.split(',').map((e, i) => ["substring" (i 1), e.trim()])));
return obj;
}
- 獲取物件的值以獲取物件
Object.values陣列{ title, string } forEach物件,設定.string為通過將字串中的每個逗號分隔值轉換為格式條目而創建的物件[substringN, value]
演示:
var testObject = {
tests1: {
title: "random title",
string: "somestring, other string, and anotherString",
},
tests2: {
title: "other random title",
string: "thisString, thatString, a String there",
},
}
function splitStrings(obj) {
Object.values(obj).forEach(val => val.string = Object.fromEntries(val.string.split(',').map((e, i) => ["substring" (i 1), e.trim()])));
return obj;
}
splitStrings(testObject);
console.log(testObject);
如果你想要一個子字串陣列,你可以這樣做:
function splitStrings(obj) {
Object.values(obj).forEach(val => val.string = val.string.split(',').map(e=>e.trim());
return obj;
}
uj5u.com熱心網友回復:
var testObject = {
tests1: {
title: "random title",
string: "somestring, other string, and anotherString"
},
tests2: {
title: "other random title",
string: "thisString, thatString, a String there"
}
};
testObject.tests1.string = testObject.tests1.string.split(",");
testObject.tests2.string = testObject.tests2.string.split(",");
console.log(testObject);
此代碼的輸出是:
{
tests1: {
title: 'random title',
string: [ 'somestring', ' other string', ' and anotherString' ]
},
tests2: {
title: 'other random title',
string: [ 'thisString', ' thatString', ' a String there' ]
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/421964.html
標籤:
