![](/img/trans.png)
[英]Converting an array of strings, where each string is a key value pair, to an object
[英]converting string array into a key value pair object
我得到的輸出看起來像這樣
var x = ["title: x_one", " description: 1", " value: 4"]
其中x[0]
返回title: x_one
這是一個字符串。 我無法閱讀標題的屬性。 我如何將其轉換為對象,以便最終我能夠遍歷數組並讀取標題,描述和值等屬性。
我試圖通過jquery做到這一點
我一直在尋找解決方案,但還沒找到。 如果有任何我遺失的東西,我將非常感謝,如果有其他人擁有並且可以指出我
循環遍歷數組,將值拆分為:
字符。 然后在對象中使用第一部分作為屬性名稱,第二部分作為值。
var obj = {};
for (var i = 0; i < x.length; i++) {
var split = x[i].split(':');
obj[split[0].trim()] = split[1].trim();
}
試試這個功能我已經測試過了
var a=new Array();
for(var i=0;i<x.length;i++){
var tmp=x[i].split(":")
a[tmp[0]]=tmp[1]
}
使用更新語言的更新版本
const splitStr = (x) => {
const y = x.split(':');
return {[y[0].trim()]: y[1].trim()};
}
const objects = ["title: x_one", " description: 1", " value: 4"].map(splitStr)
console.log(objects)
假設在創建此數組之前有一個對象,則無需將其轉換為任何對象。 使用jQuery,你可以獲得價值和關鍵。
$.each( obj, function( key, value ) {
alert( key + ": " + value );
});
如果這是最終輸出,那么在循環時可以使用String.prototype.split。
剛碰到這個。 這是OP原始陣列的另一種解決方案。
var x = ["title: x_one", " description: 1", " value: 4"]
function mapper(str)
{
var o = {};
strArr = str.split(":");
o[strArr[0].trim()] = strArr[1].trim();
return o;
}
var resultArray = x.map(mapper);
console.log(resultArray[0].title);
console.log(resultArray[1].description);
console.log(resultArray[2].value);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.