Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.0k views
in Technique[技术] by (71.8m points)

如何通过一个字符串路径来访问修改对象属性?

我有一个多层级的对象结构大概是这样的:

var data=[
    {
        "title": "节点1",
        "key": "0-1",
        "children": [{
            "title": "子节点1",
            "key": "0-1-1"
        }]
     },
     {
        "title": "节点2",
        "key": "0-2",
        "children": [{
            "key": "0-2-1",
            "title": "未命名"
        }]
      }];

我要修改某个元素的属性,常规操作不应该是这样嘛:

data['1']['children']['0']['title']="小明";

为了得到这一连串方括号访问路径,我通过扁平化来搜索匹配元素,这样我就得到了这样的数据格式:

  var flatData={
    "['0']['title']": "节点1",
    "['0']['key']": "0-1",
    "['0']['children']['0']['title']": "子节点1",
    "['0']['children']['0']['key']": "0-1-1"
    "['1']['title']": "节点2",
    "['1']['key']": "0-2",
    "['1']['children']['0']['key']": "0-2-1",
    "['1']['children']['0']['title']": "未命名"
};

扁平化后,左边的key值都是字符串,现在我就卡在这一步,怎么把这个字符串拼到data后面,来达到访问修改元素的目的?

data和"['1']['children']['0']['title']"

这个对象和字符串怎么结合起来?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

给个思路,设对象为data

  1. "['0']['title']"拆分为['0', 'title'],结果设为keys
  2. 判断keys长度是否<2,满足则直接以data[keys[0]]取值并退出,否则继续
  3. 0 - data.length - 2的范围内依次对data进行data[keys[i]]取值
  4. 最后一次取值的结果设为r,即结果为r[keys[keys.length - 1]]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...