skip to Main Content

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


  1. You could get the values and check if a value is an object, then get values or take this value.

    const
        flat = o => o && typeof o === 'object'
            ? Object.values(o).flatMap(flat)
            : [o],
        data = { 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] } },
        result = flat(data);
        
    console.log(result);
    Login or Signup to reply.
  2. If number of items is always the same you can do 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];
    
    const MyObject = {
      String: MyArray[0],
      Number: MyArray[1],
      Array2D: [MyArray.slice(2, 5), MyArray.slice(5, 8), MyArray.slice(8, 11)],
      Array1D: MyArray.slice(11, 20),
      Struct: {
        Number: MyArray[21],
        Boolean: MyArray[22],
        Array1d: MyArray.slice(23, 33)
      }
    }
    
    console.log(MyObject)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search