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

Categories

If I have array:

var arr = [
 {
  text: "something",
  child: [
   {
    text: "something child",
    child: [..]
   },..
  ]
 },..
];

Is ther any more efficient way exept rebuilding whole array with updated value by using for() to edit element when I have array of indexes:

var index = [0, 0];

to do this:

arr[0]["child"][0]["text"] = "updated value";

This is just small example but arr will be sometimes 1 level depth sometimes 12, etc. And value I need to update sometimes is in first level:

arr[0]["text"] = "updated value"
See Question&Answers more detail:os

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

1 Answer

You could iterate the indices and update text property at the end.

function update(child, indices, value) {
    indices.reduce((o, i) => o.child[i], { child }).text = value;
}

var array = [{ text: "something", child: [{ text: "something child", child: [] }] }];

update(array, [0, 0], 'foo');

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...