1

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...

3
  • 2
    There is no such thing as a JSON object. Commented 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 ;) Commented Apr 3, 2018 at 20:54
  • And reflect ineptitude in the process of doing so :0 Commented Apr 3, 2018 at 20:55

3 Answers 3

2

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()`

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

1 Comment

very nice! Works great
2

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);

Comments

0

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);

4 Comments

I know about looping through the arrays, I wanted to learn how to utilize built in methods to do it
@MattE Ok, added one more example
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.
@StephenP My bad. Removed it.

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.