0

I am trying to build JSON from two array. One array contains field_name and other contains field_value of corresponding field_name

    var field_name = ["sys_id","country","calendar_integration","user_password","last_login_time"]
var field_value = ["6816f79cc0a8016401c5a33be04be441","United State","Outlook","Password1","2019-03-19 09:48:41"];

Expected output:

output = { "sys_id" : "6816f79cc0a8016401c5a33be04be441",
        "country" : "United State",
        "calendar_integration" : "Outlook",
        "user_password": "Password1",
        "last_login_time": "2019-03-19 09:48:41"
        }

Anyone can help here, how to achieve this in JavaScript.

snowcoder
  • 481
  • 1
  • 9
  • 23
  • Possible duplicate of [Merge two arrays into one Json object](https://stackoverflow.com/questions/30124979/merge-two-arrays-into-one-json-object) – GuillaumeRZ Mar 19 '19 at 19:31

3 Answers3

1

You can do that using reduce().Set value from field_name at index i as key and value as field_value at current index

var field_name = ["sys_id","country","calendar_integration","user_password","last_login_time"]
var field_value = ["6816f79cc0a8016401c5a33be04be441","United State","Outlook","Password1","2019-03-19 09:48:41"];

let res = field_name.reduce((ac,a,i) => ({...ac,[a]:field_value[i]}),{});
console.log(res);

You can also use forEach() in the same way.

var field_name = ["sys_id","country","calendar_integration","user_password","last_login_time"]
var field_value = ["6816f79cc0a8016401c5a33be04be441","United State","Outlook","Password1","2019-03-19 09:48:41"];
let obj = {};
field_name.forEach((a,i) => obj[a] = field_value[i]);
console.log(obj)
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
1

You can try something like that if both array are always with the same size :

let JSONOutput = {}

for (let i = 0; i < firstArray.length; i++) {
    JSONOutput[firstArray[i]] = secondArray[i];
}
GuillaumeRZ
  • 2,656
  • 4
  • 19
  • 35
0

Check this solution

var output = {};
field_name.forEach((field, index) => {
     output[field] = field_value[index];
 });
H.K
  • 1
  • 1
  • user8276566 Welcome to SO and thanks for your help. Will be nice if you can explain a bit why your answer will solve the question to give it the right context – Tamir Klein Mar 19 '19 at 19:43