0

I have JS object like this. The large numbers is presorted datetimes:

{
   "param1" : [
      [1607558636000, 937.85],
      [1607561924000, 937.6],
      [1607610353000, 939.02],
      [1607610508000, 939.04],
   ],
   "param2" : [
      [1607558636000, 20.62],
      [1607561924000, 16.35],
      [1607610353000, 19.17],
      [1607610608000, 22.01],
   ],
}

And want to make it look like this:

{
    1607558636000 : {
      "param1" : 937.85,
      "param2" : 20.62
    },
    1607561924000 : {
      "param1" : 937.6,
      "param2" : 16.35
    },
    1607558636000 : {
      "param1" : 937.85,
      "param2" : 20.62
    },
    1607610508000 : {
      "param1" : 939.04,
      "param2" : null // no value for this parameter in this datetime
    },
    1607610608000 : {
      "param1" : null, // no value for this parameter in this datetime
      "param2" : 22.01
    },
},

Cant figure out. Stuck all day with code in cycle in cycle in cycle, etc.......

2
  • Something like: create a set of all of the first elements in all of the tuples in param1 and param2, iterate over the set accessing each of the params from each of the original arrays, returning an object. Commented Dec 15, 2020 at 16:19
  • Is there param3 too because i can see ... Before closing the } Commented Dec 15, 2020 at 16:42

1 Answer 1

1

You first need to iterate over the keys in the input data, which will be the keys in the output data objects, then iterate over each of the values therein to build your output objects.

Here is a javascript implementation.

/*
 * Create an object to hold our output data.
 */
const resultSet = {};

/**
 * Loop over each of the keys from the input, eg.
 * 'param1', 'param2', etc.
 */ 
Object.entries(inputSet).map(([param, value]) => {
  /**
   * Loop over the values for the current parameter. 
   * dataKey is some key like `1607558636000`, and 
   * value is the value for that key and parameter, 
   * eg. 939.02
   */
  value.forEach(([dataKey, value]) => {
    /**
     * If the output data already has an entry with the 
     * given data key, create a new parameter with the
     * current param name and assign the value
     */
    if (resultSet[dataKey]) {
      resultSet[dataKey][param] = value;
    /**
     * If no such key exists, create a new object and 
     * add it to the output data.
     */
    } else {
      resultSet[dataKey] = { [param]: value };
    }
  });
});

console.log(resultSet);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you man! You made my day! Now Its so simple and clean.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.