Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

js 数组内嵌对象(json结构),知道路径怎么去修改内容?

在js中定义了一个数组:

[
  {
    "t": "h",
    "c": [
      {
        "t": "t",
        "c": "aaaa"
      },
      {
        "t": "t",
        "c": "bbbbbbbb"
      },
      {
        "t": "t",
        "c": "cccccccc"
      }
    ]
  }
]

现在我有一个路径[0, "c", "0"]可以获取到内部aaaa这一个节点,我现在想通过该路径去修改这一个节点,怎么才能做到?


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

1 Answer

0 votes
by (71.8m points)

Lodash 好用啊

_.set(obj, path, value) 就可以 (在文档目录上面的搜索栏搜索 set,在 Object 分类下)

官方示例:

var?object?=?{?'a':?[{?'b':?{?'c':?3?}?}]?};

_.set(object,?'a[0].b.c',?4);

console.log(object.a[0].b.c);

//?=>?4

_.set(object,?['x',?'0',?'y',?'z'],?5);

console.log(object.x[0].y.z);

//?=>?5

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...