Array of objects find key name and merge the values

Viewed 78

My array like is:

array = [{
  "name": "obj0_property0",
  "url": "picture1"
}, {
  "name": "obj1_property0",
  "url": "picture1"
}, {
  "name": "obj0_property1",
  "url": "picture2"
}]

I want output like this in JavaScript:

array[{
  "obj0": ["picture1","picture2"]
}, {
  "obj1": ["picture1"]
}]

I want to find array key name obj0 and obj1 and merge picture values

3 Answers

reduce is a good method for transforming arrays

var array = [{"name":"obj0_property0","url":"picture1"},{"name":"obj1_property0","url":"picture1"},{"name":"obj0_property1","url":"picture2"}]

var result = array.reduce((acc, {name, url}) => {
  // getting object key obj0, obj1
  const objKey = name.split(`_`)[0];
  
  // trying to find in accumulator object with same key as objKey
  const objInArray = acc.find(accitem => objKey in accitem);

  // if found
  if (objInArray) {
    // add another url
    objInArray[objKey].push(url)
  } else {
    // if not found add new object
    acc.push({[objKey]: [url]})
  }
  return acc;
}, []) // [] is initial value of accumulator

console.log(result)

// array [{"obj0":"picture1","picture2"},{"obj1":"picture1"}]

You can use reduce method and store all url in array:

const result = Object.entries(array.reduce((a, {name, url})=> {
    let key = name.substring(0, 4);
    a[key] = a[key] || [];
    a[key].push(url);
    return a;
},{})).map(([k, v])=> ({[k]: v}));

An example:

let array = [
    {"name":"obj0_property0","url":"picture1"},
    {"name":"obj1_property0","url":"picture1"},
    {"name":"obj0_property1","url":"picture2"}
];

const result = Object.entries(array.reduce((a, {name, url})=> {
    let key = name.substring(0, 4);
    a[key] = a[key] || [];
    a[key].push(url);
    return a;
},{})).map(([k, v])=> ({[k]: v}));
console.log(result);

Simple Array.prototype.reduce() may regroup your source array easily:

const array = [{"name":"obj0_property0","url":"picture1"},{"name":"obj1_property0","url":"picture1"},{"name":"obj0_property1","url":"picture2"}],
      result = array.reduce((r,{name,url}) => {
        const [key] = name.split('_'),
              match = r.find(item => key in item)
        match ? match[key].push(url) : r.push({[key]:[url]})
        return r
      },[])

console.log(result)
.as-console-wrapper {min-height:100%;}

Related