在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ 字符串object變量解析問題

字符串object變量解析問題

a可能是這樣
var a = {
    result: {
        item: [1,2]
    }
}
也可能是這樣
var a = {
    result: []
}
也可能是這樣
var a = {
    other: []
}

我要封裝根據(jù)字符串來找到a對(duì)應(yīng)key的value值

// 這個(gè)str傳有可能是'result', 'result.items', 'other'
function test (str) {
    // a[str] ???
}
// 那么我這里這么寫才能使得上面的object a['變量']解析出來呢?
回答
編輯回答
安若晴

preact源碼里有這樣的一個(gè)函數(shù),可參考
let delve = (obj, key) => (key.split('.').map(p => (obj = obj && obj[p])), obj);

2017年1月25日 22:25
編輯回答
奧特蛋

var a = {

result: {
    item: [1,2]
}

}
var b = {

result: []

}
var c = {

other: []

}
// 這個(gè)str傳有可能是'result', 'result.items', 'other'
function test (o, str) {

let a = str.split('.')
let r = o;
a.map((item, index)=> {
    r = r[item]
})
return r;

}
let t1 = test(a, 'result.item')
let t2 = test(b, 'result')
let t3 = test(c, 'other')
console.log(t1, t2, t3)

2017年1月25日 21:25
編輯回答
墨小白

var obj={
f1:{f2:{f3:2}}
}
var key="f1.f2.f3"

var value=eval("obj."+key);
沒那么復(fù)雜噢

2018年2月26日 14:03
編輯回答
伴謊

如果傳入的參數(shù)約定好,獲取內(nèi)部的值時(shí),屬性是按從外往內(nèi),用.連接起來的字符串。那么就在test()內(nèi)部,把參數(shù)str拆分開,從外向內(nèi)依次尋找即可:

function test(obj, str){
    let params = str.split('.'), // 拆分
        len = params.length,
        item = obj;
    
    for(let i=0; i<len; i++){
        item = item[params[i]]
        if( !item ){
            return 'not found';
        }
    }
    return item;
}

執(zhí)行:

var a = {
    result: {
        item: [1,2]
    }
}
test(a, 'result.item'); // [1, 2]

var a = {
    result: []
}
test(a, 'result.item'); // "not found"
test(a, 'result'); // []

var a = {
    other: []
}
test(a, 'other'); // []
test(a, 'result'); // "not found"
2018年5月23日 16:35
編輯回答
孤影
function get( obj, path ) {
    return path.split( '.' ).reduce( ( target, key ) => target[ key ], obj )
}

const obj = { a: { b: 2 } }
console.log( get( obj, 'a.b' ) )    // 2
2018年1月10日 16:51
編輯回答
疚幼
function test (obj, str) {
 return str.split('.').reduce(function(iter, v){return iter && iter[v]}, obj)
}

test(a, 'result.item')
2017年4月8日 22:19
編輯回答
放開她
function getVal(str) {
    const attr = str.split('.');
    let final = a;
    for (let val of attr) {
        final = final[val];
    }
    return final;
}
2018年4月27日 05:01