原對(duì)象
let obj1 = {
data: [
{
news_id: 51182,
title:
"Teslamask's American Business Relations: The government does not pay billions to build factories",
source: "AI Finance",
members: [
{
title: [
{
news_id: 51184,
title:
"iPhone X Review: Innovative future with real black technology",
source: "Netease phone",
},
],
},
],
},
],
}; //原對(duì)象
根據(jù)路徑修改某個(gè)屬性值 函數(shù)
/*
* objectStr 字符串格式 頂層數(shù)據(jù)層級(jí)名稱
* path 屬性的路徑
* val 要改成的值
*/
function findMod(objectStr, path, val) {
let props = path.split(".");
let th = "";
for (let i = 0; i < props.length; i++) {
th += "['" + props[i] + "']";
}
//判斷是對(duì)象還是字符串
let isObj = new Function("return " + objectStr + th);
let e = new Function();
if (typeof isObj() == "object") {
e = new Function(objectStr + th + "=" + val);
} else if (typeof isObj() == "string") {
e = new Function(objectStr + th + '="' + val + '"');
}
e();
}
函數(shù)調(diào)用
根據(jù)路徑修改一個(gè)字符串屬性值
findMod(
"obj1",
"data.0.members.0.title.0.title",
"根據(jù)路徑修改一個(gè)屬性值(字符串)"
);
console.log(obj1);
document.write(obj1["data"]["0"]["members"]["0"]["title"]["0"]["title"]);
根據(jù)路徑修改一個(gè)對(duì)象屬性值
findMod("obj1", "data.0.members.0.title", '[{"a":"hhh"},{"a":"888"}]'); //修改一個(gè)子對(duì)象
console.log(obj1);
根據(jù)路徑修改一個(gè)對(duì)象屬性值