I was wanting to see if there is a relatively simple method for doing this as I can use the following:
var arr = [ "Client", "ActType", "CallRepType"];
var arr2 = [ "ECF", "Meeting", "Call Report"]
var myobj = arr2.map(value => ({'Client': arr2[0], 'ActType': arr2[1], 'CallRepType': arr2[2]}));
But I get the same correct object 3 times in a row...I simply want a single object returned that looks like:
{Client: 'ECF', ActType: 'Meeting', CallRepType: 'Call Report'}
I know I can loop through both arrays but I was hoping to get a solution using map, reduce or taking advantage of spread in javascript...
Jonathan M
17.5k9 gold badges61 silver badges95 bronze badges
asked Apr 3, 2018 at 20:52
MattE
1,1121 gold badge15 silver badges37 bronze badges
-
2There is no such thing as a JSON object.Randy Casburn– Randy Casburn2018年04月03日 20:53:12 +00:00Commented Apr 3, 2018 at 20:53
-
2^ There's also no such thing as an ATM machine or a PIN number, but people still claim to use both ;)Obsidian Age– Obsidian Age2018年04月03日 20:54:05 +00:00Commented Apr 3, 2018 at 20:54
-
And reflect ineptitude in the process of doing so :0Randy Casburn– Randy Casburn2018年04月03日 20:55:04 +00:00Commented Apr 3, 2018 at 20:55
3 Answers 3
A faster solution that uses Array.prototype.forEach():
var arr = [ "Client", "ActType", "CallRepType"];
var arr2 = [ "ECF", "Meeting", "Call Report"]
var result = {};
arr.forEach((el, i) => { result[el] = arr2[i]; });
console.log(result);
Array.prototype.forEach()`
answered Apr 3, 2018 at 21:03
Randy Casburn
14.2k1 gold badge20 silver badges32 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
MattE
very nice! Works great
This a solution that uses Array.reduce() to create the object:
const arr = [ "Client", "ActType", "CallRepType"];
const arr2 = [ "ECF", "Meeting", "Call Report"]
const myobj = arr.reduce((r, key, i) => {
r[key] = arr2[i];
return r;
}, {});
console.log(myobj);
answered Apr 3, 2018 at 20:55
Ori Drori
196k32 gold badges243 silver badges233 bronze badges
Comments
You can loop through the array and do it:
var arr = [ "Client", "ActType", "CallRepType"];
var arr2 = [ "ECF", "Meeting", "Call Report"];
var len = arr.length;
var myObj = {};
for (var i = 0; i < len; i++) {
var myObject = {};
myObj[arr[i]] = arr2[i]
// myObj.push = myObject;
}
console.log(myObj);
answered Apr 3, 2018 at 21:02
Pritam Banerjee
19.1k10 gold badges97 silver badges113 bronze badges
4 Comments
MattE
I know about looping through the arrays, I wanted to learn how to utilize built in methods to do it
Pritam Banerjee
@MattE Ok, added one more example
Stephen P
Neither method produces the OP's desired output, an object with the members
{Client: 'ECF', ActType: 'Meeting', CallRepType: 'Call Report'} not an array of objects each with one member.Pritam Banerjee
@StephenP My bad. Removed it.
lang-js