9

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.

2

3 Answers 3

10

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)

Sign up to request clarification or add additional context in comments.

Comments

5

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)

3 Comments

Hi @brk, the reason I didnt use reduce to begin with is I merge together 2 arrays inside the map function jsfiddle.net/cqraohy5/1 This is how this question looks with the merge but doesnt work with the reduce method
@DanielJ map can never return object.
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?
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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.