0

My two arrays are:

const values = ['Master Clean', '45', '650']
const names = ['servicemenus.$.name', 'servicemenus.$.duration', 'servicemenus.$.cost']

The result should be like this:

{ 'servicemenus.$.name':'Master Clean',  'servicemenus.$.duration': '45', 'servicemenus.$.cost': 650}
Badacadabra
  • 8,043
  • 7
  • 28
  • 49

5 Answers5

1

Since I think that you know these two Arrays needs to be the same length at all time. This for loop could help you:

const values = ['Master Clean', '45', '650']
const names = ['servicemenus.$.name', 'servicemenus.$.duration', 'servicemenus.$.cost']
var obj = {}
for (var i = 0; i < names.length; i++) {
  //or check with: if (values.length > i) { assignment }
  obj[names[i]] = values[i];
}
console.log(obj);

Output will be this: Object { servicemenus.$.name: "Master Clean", servicemenus.$.duration: "45", servicemenus.$.cost: "650" }

For completion, I found this Question could help you too: Merge two arrays into one Json object

Community
  • 1
  • 1
0

From the assumption that the two arrays are always equal length, we can use one of them as the basis for a loop where we build the object:

let resultingObject = {};
names.forEach((name, i) => {
    resultingObject[name] = values[i];
});

console.log(resultingObject);
Lennholm
  • 7,205
  • 1
  • 21
  • 30
0

You can reduce an array to a single value (object in your case). Reduce function accepts accumulator, current value and index which you can use to reference a value in the second array. Object.assign constructs an object with your keys/values.

const values = ['Master Clean', '45', '650'];
const names = ['servicemenus.$.name', 'servicemenus.$.duration', 'servicemenus.$.cost'];

const res = names.reduce((acc, cur, i) => Object.assign(acc, {[cur]: values[i]}), {});

console.log(res)
Egor Stambakio
  • 17,836
  • 5
  • 33
  • 35
0

You can work with the index of the array in a forEach to refer to the other and dynamically build the object keys:

const values = ['Master Clean', '45', '650']
const names = ['servicemenus.$.name', 'servicemenus.$.duration', 'servicemenus.$.cost']

let update = { };

names.forEach( (name,idx) => {
  update[name] = values[idx];
});

And that gives you the result

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
0

And with for in,loop through the object properties and assign it new object

var newobj = {};
for( var i in names){
newobj[names[i]] = values[i];
}
console.log(newobj);
Arun Kumaresh
  • 6,211
  • 6
  • 32
  • 50