Javascript merge array of objects based on incrementing key

Viewed 152

This is what I have: I want to merge object which key begins with "path-"+i . And to strip "path-i" from keys in end result.

  var arr = [
  {
    "key": "path-0-mp4",
    "value": [
      "media/video/01.mp4",
      "media/video/01_hd.mp4"
    ]
  },
  {
    "key": "path-0-quality",
    "value": [
      "720p",
      "1080p"
    ]
  },
  {
    "key": "path-1-mp4",
    "value": [
      "media/video/02.mp4",
      "media/video/02_hd.mp4"
    ]
  },
  {
    "key": "path-1-quality",
    "value": [
      "SD",
      "HD"
    ]
  }

]

This is a desired result:

 var arr = [
        [
              {
                "mp4": "media/video/01.mp4",
                "quality": "720p"
              },
              {
                "mp4": "media/video/01_hd.mp4",
                "quality": "1080p"
              },
        ],
        [
              {
                "mp4": "media/video/02.mp4",
                "quality": "SD"
              },
              {
                "mp4": "media/video/02_hd.mp4",
                "quality": "HD"
              },
        ],
]

I started doing something but its not even close:

var key, new_key, value,j=0, z=0, parr = [], obj;
for(var i = 0;i<a.length;i++){
    console.log('item:' ,a[i])
    key = a[i].key, value = a[i].value
    if(key.indexOf('path-'+j.toString()) > -1){
        new_key = key.substr(key.lastIndexOf('-')+1)
        console.log(key, new_key, value)
        for(var z = 0;z<value.length;z++){
            parr.push({[new_key]: value[z] })
        }
    }
}

console.log(parr)

[
  {
    "mp4": "media/video/01.mp4"
  },
  {
    "mp4": "media/video/01_hd.mp4"
  },
  {
    "quality": "720p"
  },
  {
    "quality": "1080p"
  }
]

edit:

Array could petencially hols different keys that would need grouping in the same way, for example:

    var arr = [
  {
    "key": "path-0-mp4",
    "value": [
      "media/video/01.mp4",
      "media/video/01_hd.mp4"
    ]
  },
  {
    "key": "path-0-quality",
    "value": [
      "720p",
      "1080p"
    ]
  },
  {
    "key": "path-1-mp4",
    "value": [
      "media/video/02.mp4",
      "media/video/02_hd.mp4"
    ]
  },
  {
    "key": "path-1-quality",
    "value": [
      "SD",
      "HD"
    ]
  },
  {
    "key": "subtitle-0-label",
    "value": [
      "English",
      "German",
      "Spanish"
    ]
  },
  {
    "key": "subtitle-0-src",
    "value": [
      "data/subtitles/sintel-en.vtt",
      "data/subtitles/sintel-de.vtt",
      "data/subtitles/sintel-es.vtt"
    ]
  },
  {
    "key": "subtitle-1-label",
    "value": [
      "German",
      "Spanish"
    ]
  },
  {
    "key": "subtitle-1-src",
    "value": [
      "data/subtitles/tumblr-de.vtt",
      "data/subtitles/tumblr-es.vtt"
    ]
  }
]

This is a desired result (create new array for each different key):

 var arr = [
        [
              {
                "mp4": "media/video/01.mp4",
                "quality": "720p"
              },
              {
                "mp4": "media/video/01_hd.mp4",
                "quality": "1080p"
              },
        ],
        [
              {
                "mp4": "media/video/02.mp4",
                "quality": "SD"
              },
              {
                "mp4": "media/video/02_hd.mp4",
                "quality": "HD"
              },
        ],
],
arr2 = [        
    [
        {
            "label": "English",
            "src": "data/subtitles/sintel-en.vtt",
        },
        {
            "label": "German",
            "src": "data/subtitles/sintel-de.vtt"
        },
        {
            "label": "Spanish",
            "src": "data/subtitles/sintel-es.vtt"
        }
    ],
    [
        {
            "label": "Spanish",
            "src": "data/subtitles/tumblr-es.vtt",
        },
        {
            "label": "German",
            "src": "data/subtitles/tumblr-de.vtt"
        }
    ]
 ]
4 Answers

You could split the key property, omit the first path and take the rest as index and key. Then create a new array, if not exists and assign the values.

var data = [{ key: "path-0-mp4", value: ["media/video/01.mp4", "media/video/01_hd.mp4"] }, { key: "path-0-quality", value: ["720p", "1080p"] }, { key: "path-1-mp4", value: ["media/video/02.mp4", "media/video/02_hd.mp4"] }, { key: "path-1-quality", value: ["SD", "HD"] }],
    result = data.reduce((r, { key, value }) => {
        let [, i, k] = key.split('-');
        r[i] = r[i] || [];
        value.forEach((v, j) => (r[i][j] = r[i][j] || {})[k] = v);
        return r;
    }, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

If you like to group by the first part of key, you could take an object with this group as key and assign the rest as above.

var data = [{ key: "path-0-mp4", value: ["media/video/01.mp4", "media/video/01_hd.mp4"] }, { key: "path-0-quality", value: ["720p", "1080p"] }, { key: "path-1-mp4", value: ["media/video/02.mp4", "media/video/02_hd.mp4"] }, { key: "path-1-quality", value: ["SD", "HD"] }, { key: "subtitle-0-label", value: ["English", "German", "Spanish"] }, { key: "subtitle-0-src", value: ["data/subtitles/sintel-en.vtt", "data/subtitles/sintel-de.vtt", "data/subtitles/sintel-es.vtt"] }, { key: "subtitle-1-label", value: ["German", "Spanish"] }, { key: "subtitle-1-src", value: ["data/subtitles/tumblr-de.vtt", "data/subtitles/tumblr-es.vtt"] }],
    result = data.reduce((r, { key, value }) => {
        let [group, i, k] = key.split('-');
        if (!r[group]) r[group] = [];
        if (!r[group][i]) r[group][i] = [];
        value.forEach((v, j) => {
            if (!r[group][i][j]) r[group][i][j] = {};
            r[group][i][j][k] = v;
        });
        return r;
    }, {});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

I am new to this and a beginner, is this the correct approach?

const a = [{ "key": "path-0-mp4", "value": [ "media/video/01.mp4", "media/video/01_hd.mp4" ] }, { "key": "path-0-quality", "value": [ "720p", "1080p" ] }, { "key": "path-1-mp4", "value": [ "media/video/02.mp4", "media/video/02_hd.mp4" ] }, { "key": "path-1-quality", "value": [ "SD", "HD" ] } ];

var resp = [];
for (let i = 0; i < a.length; i++) {
  var inst = a[i];
  var key = inst["key"];
  for (let j = 0; j < inst.value.length; j++) {
    var index = key.split("-")[1];
    var keyinst = key.split("-")[2];
    if (!resp[index]) {
      resp[index] = [];
    }
    if (!resp[index][j]) {
      resp[index][j] = {};
    }
    resp[index][j][keyinst] = inst.value[j];
  }
}
console.log(resp);

I find this easier to read and grasp

You can save an assignment if you use reduce

const arr = [{ "key": "path-0-mp4", "value": [ "media/video/01.mp4", "media/video/01_hd.mp4" ] }, { "key": "path-0-quality", "value": [ "720p", "1080p" ] }, { "key": "path-1-mp4", "value": [ "media/video/02.mp4", "media/video/02_hd.mp4" ] }, { "key": "path-1-quality", "value": [ "SD", "HD" ] } ];

newArr = [];
arr.filter(item => item.key.endsWith("mp4"))
     .forEach(item => item.value
       .forEach((val, i) => newArr.push({
          "mp4": val, 
      "quality": arr.find(qItem => qItem.key === item.key.replace("mp4", "quality")).value[i]}
     )
   )
 )

console.log(newArr)

Here is Nina's version in an unobfuscated version

var data = [{ key: "path-0-mp4", value: ["media/video/01.mp4", "media/video/01_hd.mp4"] }, { key: "path-0-quality", value: ["720p", "1080p"] }, { key: "path-1-mp4", value: ["media/video/02.mp4", "media/video/02_hd.mp4"] }, { key: "path-1-quality", value: ["SD", "HD"] }],

  result = data.reduce((resultArray, { key, value }) => {
        let [, idx, suffix] = key.split('-');
        resultArray[idx] = resultArray[idx] || [];
        value.forEach((val, i) => (resultArray[idx][i] = resultArray[idx][i] || {})[suffix] = val);
        return resultArray;
    }, []);

console.log(result);

The only odd thing I did here was using an object as a lookup table to help with the speed complexity. If you have any questions let me know.

const arr = [{ "key": "path-0-mp4", "value": [ "media/video/01.mp4", "media/video/01_hd.mp4" ] }, { "key": "path-0-quality", "value": [ "720p", "1080p" ] }, { "key": "path-1-mp4", "value": [ "media/video/02.mp4", "media/video/02_hd.mp4" ] }, { "key": "path-1-quality", "value": [ "SD", "HD" ] } ];


const result = arr.reduce((table, item) => {
  // Getting "path-1" from "path-1-quality" 
  const pathValues = item.key.split('-');
  const pathValue = pathValues[0] + '-' + pathValues[1];
  // Getting "quality" from "path-1-quality" 
  const key = pathValues[2];
  
  // Get Index from table if already registered paths
  let tIndex = table.indexLookup[pathValue]; 
  
  // If there is no registered index register one
  if (tIndex === undefined) {
    // reassign index to new location
    tIndex = table.result.length;
    // register the index
    table.indexLookup[pathValue] = tIndex;
    table.result.push([]);
  }
  
  // Assign values
  item.value.forEach((value, i) => {
   const arr = table.result[tIndex] || [];
    arr[i] = arr[i] || {}
    arr[i][key] = value;
    table.result[tIndex] = arr;
  })
  return table
}, {
  indexLookup : {},
  result: []
}).result


console.log(result)

Related