7

Sorry if the title is misleading I'm not sure how to accurately describe what I am looking for.

I have an array result which I want to turn into multiple objects where each objects property is the field Name Test I need to keep my result.map method as I use it to merge result with data

  result = [{
      "Name Test": "Yellow",
      Count: 124,

    },
    {
      "Name Test": "Black",
      Count: 124,
    },
    {
      "Name Test": "Blue",
      Count: 124,
    }
  ];

  data = [{
      "Name Test": "Yellow",
      pop: 1
    },
    {
      "Name Test": "Black",
      pop: 1
    },
    {
      "Name Test": "Blue",
      pop: 1
    }
  ];


result = result.map((obj1, index) => {
    const obj2 = data[index];
    return {
        [obj1["Name Test"].toUpperCase()]: {
            Count: obj1.Count,
            pop: obj2.pop,
        }
    };
});
console.log(JSON.stringify(result))

This code returns an array of objects which is not what I want as I need to be able to use result["YELLOW"] later in my code. I therefore need the result to be in this format, with no arrays.

{  
   "YELLOW":{  
      "Count":124,
      "pop":1
   },
   "BLACK":{  
      "Count":124,
      "pop":1
   },
   "BLUE":{  
      "Count":124,
      "pop":1
   }
}

I hope this makes sense and I feel I am very close to what I want and just am missing something small, but every way I have tried to make this work turns into a syntax error.

DanielJ
  • 729
  • 2
  • 7
  • 26
  • You should look at [array.reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce) – ray May 18 '19 at 04:29
  • Possible duplicate of [How do I convert array of Objects into one Object in JavaScript?](https://stackoverflow.com/questions/19874555/how-do-i-convert-array-of-objects-into-one-object-in-javascript) – Herohtar May 18 '19 at 04:31

3 Answers3

9

map() will always return an array.

  • You should use reduce() and set accumulator to empty object {}

  • Use the destructuring and spread syntax to isolate Name Test and other properties.

  • Set the property of accumulator whose key is "Name Test" property of each object and its value is rest of the object.

const arr = [{ "Name Test": "Yellow", Count: 124, pop: 1 }, { "Name Test": "Black", Count: 124, pop: 1 }, { "Name Test": "Blue", Count: 124, pop: 1 } ];

const res = arr.reduce((ac,{["Name Test"]:x,...rest}) => (ac[x] = rest,ac),{})

console.log(res)
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
4

map will create a new array. So you can use reduce and pass an empty object in the accumulator

let result = [{
    "Name Test": "Yellow",
    Count: 124,
    pop: 1
  },
  {
    "Name Test": "Black",
    Count: 124,
    pop: 1
  },
  {
    "Name Test": "Blue",
    Count: 124,
    pop: 1
  }
];

let newResult = result.reduce(function(acc, curr) {
  // acc is accumulator which is the required object.
  // this will create a nee key in accumulator and will set its value
  acc[curr['Name Test'].toUpperCase()] = {
    Count: curr.Count,
    pop: curr.pop
  }
 return acc;
}, {}) // {} is accumulator object. This will hold the required keys and values

console.log(newResult)
brk
  • 48,835
  • 10
  • 56
  • 78
  • Hi @brk, the reason I didnt use reduce to begin with is I merge together 2 arrays inside the map function https://jsfiddle.net/cqraohy5/1/ This is how this question looks with the merge but doesnt work with the reduce method – DanielJ May 18 '19 at 04:39
  • 1
    @DanielJ map can never return object. – brk May 18 '19 at 04:41
  • I've edited my orginal question to clarify what I am asking @brk so in my case, do I need to do my merge with `map` then do the reduce method to reduce it? – DanielJ May 18 '19 at 04:43
1

It's not available in MS browsers yet, (I think), but fromEntries() is pretty nice for this. You can pass it an iterable or key.value pairs, such as the results from map().

let result = [{"Name Test": "Yellow",Count: 124,pop: 1},{"Name Test": "Black",Count: 124,pop: 1},{"Name Test": "Blue",Count: 124,pop: 1}];
let data = [{"Name Test": "Yellow",pop: 1},{"Name Test": "Black",pop: 1},{"Name Test": "Blue",pop: 1}];

let o = Object.fromEntries(result.map(({'Name Test':n, ...o}) => ([n, o])))
let d = Object.fromEntries(result.map(({'Name Test':n, ...o}) => ([n, o])))
 
console.log(Object.assign(o, d))
Mark
  • 90,562
  • 7
  • 108
  • 148