Search code examples
javascriptjoindata-structuresmappingreduce

Javascript - Reduce multidimensional object to string


Given object:

obj = {
      "zozo": {
          "buys": "6",
          "sells": "9"
      },
      "zaza": {
          "buys": "5",
          "sells": "2"
      }
}

How can I reduce this into the string zozo: buys(6) sells(9), zaza: buys(5) sells(2) ?

The best I have managed so far is:

obj = {
      "zozo": {
          "buys": "6",
          "sells": "9"
      },
      "zaza": {
          "buys": "5",
          "sells": "2"
      }
}
      
res = Object.entries(obj).reduce((x,y) => `${x}, ${y[0]}: buys(${y[1].buys}) sells(${y[1].sells})`, '');
console.log(res);
Which gives me , zozo: buys(6) sells(9), zaza: buys(5) sells(2)

I understand this is because I am passing an empty string as initial value, but if I don't do that then the function takes an array as initial value.


Solution

  • You can modify your code by joining the resulting array of strings using Array.prototype.join():

    const obj = {
      "zozo": {
        "buys": "6",
        "sells": "9"
      },
      "zaza": {
        "buys": "5",
        "sells": "2"
      }
    };
    
    const res = Object.entries(obj).reduce((accumulator, [key, value]) => {
      const entry = `${key}: buys(${value.buys}) sells(${value.sells})`;
      return accumulator.concat(entry);
    }, []).join(", ");
    
    console.log(res);