my task is it to transfer data from an array to an existing object. I have an Array with different values (Number,Strings,..) and a Object with Number,String,1-D Array, 2-D Array. Now i would like to know the smartest way to get all the data from the array MyArray to the object MyObject. For example my Object look like this:
const MyObject = {
String: '',
Number: 0,
Array2D: [[0, 0, 0], [0, 0, 0], [0, 0, 0]],
Array1D: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
Struct: {
Number: 0,
Boolean: false,
Array1D: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
}
};
And Array like this:
let MyArray [HelloWord,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,true,0,0,0,0,0,0,0,0,0,0];
Is it possible to do this in a easy way? I tried Object.key() Object.Value() Object.entities() but i was not able to solve my problem. Hope someone can help me thanks.
My first solution: MyObject to String:
let JSON = JSON.stringify(MyObject);
after that i use typeof for each array element:
MyArray.forEach(function(element){
switch(typeof(element)) {
case 'string':
JSON = JSON.replace('""', element);
break;
case 'number':
JSON = JSON.replace('-1', element.toString());
break;
case 'boolean':
JSON = JSON.replace('false', element.toString());
break;
default:
break;
}
});
Problem: I have to set each Number in MyObject to -1. Also its not possible to set a value to -1 because it all based on seach for -1 in a string and replace it.
My Goal should be: Every single value of MyArrays is registered in MyObject.
2
Answers
You could get the values and check if a value is an object, then get values or take this value.
If number of items is always the same you can do this: