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
522 views
in Technique[技术] by (71.8m points)

javascript - Updating value of multidimensional array of object

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

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

1 Answer

0 votes
by (71.8m points)

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; }

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

...