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.

1

3 Answers 3

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)

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

1 Comment

Thanks Maheer, this is perfect !!
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];
}

Comments

0

Check this solution

var output = {};
field_name.forEach((field, index) => {
     output[field] = field_value[index];
 });

1 Comment

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

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.