K
K
Kirill Petrov2017-09-23 18:38:09
JavaScript
Kirill Petrov, 2017-09-23 18:38:09

How to write to a multidimensional array/object at an address in JavaScript?

Greetings. Here I do not understand how to write data to a multidimensional array with objects at the address. For example, there is an array, an address (by the key property) and new data

var data = [
  {key:'raz', cells:[{val: '1'},{val:'razoviy'}]},
  {key:'dva', cells:[{val: '2'},{val:'vtoroy'}],children:[
    {key:'poddva', cells:[{val: '2'},{val:'podvtoroy'}],children:
    		[{key:'podpoddva', cells:[{val: '2'},{val:'podpodvtoroy'}]},{key:'raz', cells:[{val: '1'},{val:'raz'}]}]
    	},
      {key:'poddvadva', cells:[{val: '2'},{val:'podvtoroyvtoroy'}]}
  ]},
  {key:'tri', cells:[{val: '3'},{val:'trtiy'}]}
]

var adres = ['dva','poddva','raz']

var newDataCells = [{val: '1.0'},{val:'raz raz, est svyaz'}]

I don’t know how to build a script that would write data to this variable at the address. Well, just add new child objects ...

Answer the question

In order to leave comments, you need to log in

4 answer(s)
K
Kirill Petrov, 2017-09-24
@Recosh

Solved the problem like this:

var data = [
  {key:'raz', cells:[{val: '1'},{val:'razoviy'}]},
  {key:'dva', cells:[{val: '2'},{val:'vtoroy'}],children:[
    {key:'poddva', cells:[{val: '2'},{val:'podvtoroy'}],children:
    		[{key:'podpoddva', cells:[{val: '2'},{val:'podpodvtoroy'}]},{key:'raz', cells:[{val: '1'},{val:'raz'}]}]
    	},
      {key:'poddvadva', cells:[{val: '2'},{val:'podvtoroyvtoroy'}]}
  ]},
  {key:'tri', cells:[{val: '3'},{val:'trtiy'}]}
]

var adres = ['dva','poddva','raz']
var newDataCells = [{val: '1.0'},{val:'raz raz, est svyaz'}]
var lastMath
Object.traverse(data, function(node, value, key, path, depth) {
    if(typeof value == 'object' && value.key){
    let indexAdres = 0;
    if(depth > 0)
      indexAdres = depth/2
    
    if(value.key == adres[indexAdres])
      lastMath = value
    }
});
lastMath.cells = newDataCells

console.log(data)

The Object.traverse method was taken from this post https://javascript.ru/forum/project/51879-object-t...

P
Pavel Kornilov, 2017-09-23
@KorniloFF

data[0].key= 1;
data[1].key= 2;

I
Ilya Gerasimov, 2017-09-23
@Omashu

var data = [
  {key:'raz', cells:[{val: '1'},{val:'razoviy'}]},
  {key:'dva', cells:[{val: '2'},{val:'vtoroy'}],children:[
    {key:'poddva', cells:[{val: '2'},{val:'podvtoroy'}],children:
    		[{key:'podpoddva', cells:[{val: '2'},{val:'podpodvtoroy'}]},{key:'raz', cells:[{val: '1'},{val:'raz'}]}]
    	},
      {key:'poddvadva', cells:[{val: '2'},{val:'podvtoroyvtoroy'}]}
  ]},
  {key:'tri', cells:[{val: '3'},{val:'trtiy'}]}
]

var newDataCells = [{val: '1.0'},{val:'raz raz, est svyaz'}]

var obj = data.find(val => val.key == 'dva')
obj.cells = newDataCells;

console.log(data);

K
Kovalsky, 2017-09-23
@lazalu68

MDN , learn.javascript.ru

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question