Home > Software design >  Adding values to an array at specific indexes containing the data from within the array
Adding values to an array at specific indexes containing the data from within the array

Time:07-19

My initial Data looks like this:

const data = [ 
  {date: "jan.15", video: 2, chat: 1, other: 3}, 
  {date: "jan.16", video: 5, chat: 3, other: 3}
]

In order to use this data I had to turn each of these object into an array. So I did this:

   const count = data.map((item, idx)=> {
        let value = Object.values(item);
         return value
    }) || [];

which output:

[
  ["jan.15", 2, 1, 3]
  ["jan.16", 5, 3, 3]
]

However I need to add values to these arrays that include the data from the array.. So I need an output of something like this:

[
  ["jan.15", 2, "jan.15, 2", 1, "jan.15, 1", 3, "jan.15, 3"],
  ["jan.16", 5,"jan.16, 5", 3,"jan.16, 3", 3, "jan.16, 3"]
]

And Im not sure how to read the values and insert them into the array at specific points.

The date ex)jan.15 is associated with each of the following values in the array. So following each value I need to insert the data theValue to be used in my application.

CodePudding user response:

You could map over array and then do another map on Object.values.

const data = [ {date: "jan.15", video: 2, chat: 1, other: 3}, {date: "jan.16", video: 5, chat: 3, other: 3}]

const result = data.map(({ date, ...rest }) => (
  [date].concat(...Object.values(rest).map(v => (
    [v, `${date}, ${v}`]
  )))
))

console.log(result)

CodePudding user response:

here is some pice of code. we follow same as your approch Object.values to get all values from object, and we reduce it according to your condition.

const data = [ 
  {date: "jan.15", video: 2, chat: 1, other: 3}, 
  {date: "jan.16", video: 5, chat: 3, other: 3}
]

const reducedData = data.reduce((prev, curr, i) => {
    const value = Object.values(curr)
    const newValue = value.reduce((prev, curr, i, arr) => {
      if (i === 0 || i === 1) {
        prev.push(curr);
        if (i === 1) {
          prev.push(arr[0]   ', '   curr);
        }
        return prev;
      }
      prev.push(curr),
      prev.push(arr[0]   ', '   curr);
      return prev;
    }, []);
    prev.push(newValue);
    return prev;
}, []);

console.log(reducedData)

  • Related