Convert two array into JSON object - javascript

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.

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)

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];
}

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

Related

JavaScript: generated object with multiple objects inside -> one object

this is how my object looks like:
, but I need just one object like
obj = {
var: "DB3,B0",
zahl: "DB3,Int2",
zahl2: "DB3,Int4",
...
...
};
How do I convert it?
I tried different things but it all won't work inside a for loop.
I generate my Object from a string with a code like this:
var text = msg.payload;
var nt = text.split(" ");
var n = nt.length;
var add = [];
var name = [];
var ab = [];
var variables = {};
for (var i = 0; i < n; i++) {
ab[i] = nt[i].split(";");
add[i] = ab[i][0];
name[i] = ab[i][1];
variables[i] = {[name[i]] : add[i]};
}
msg.payloadvars = variables;
return msg;
I think it should be quite simple but I don't come to any solution.
input looks like
DB3,B0;var DB3,Int2;zahl DB3,Int4;zahl2 DB3,Int6;zahl3 DB3,Int8;zahl4
DB3,Int10;zahl5 .....
You could split the string by groups and then for value and key.
var string = 'DB3,B0;var DB3,Int2;zahl DB3,Int4;zahl2 DB3,Int6;zahl3 DB3,Int8;zahl4 DB3,Int10;zahl5',
target = Object.assign(
...string.split(' ').map(s => (([v, k]) => ({ [k]: v }))(s.split(';')))
);
console.log(target);
Use Array.reduce
let str = "DB3,B0;var DB3,Int2;zahl DB3,Int4;zahl2 DB3,Int6;zahl3 DB3,Int8;zahl4 DB3,Int10;zahl5";
let obj = str.split(" ").reduce((a,c) => {
let v = c.split(";");
Object.assign(a, {[v[1]]: v[0]});
return a;
}, {});
console.log(obj);
if you want to make single object then you should try this:
var variables = {};
for (var i = 0; i < n; i++) {
ab[i] = nt[i].split(";");
add[i] = ab[i][0];
name[i] = ab[i][1];
variables[name[i]] = add[i];
}
console.log(variables);

Removing "object having an array field" from an array in javascript

Here is my code:
var subMed = [ {med:'bm', sub:[ 'a' , 'b' ]} , {med:'bm', sub:[ 'c' , 'd' , 'e' ]} ];
var sal = [ {num:"1",amount:"500"} ];
var t = {Class:"1", subMeds:subMed, numOfSub:2, sals:sal };
var infoAcademic = [];
infoAcademic.push(t);
subMed = [ {med:'em', sub:[ 'p']} , {med:'bm', sub:[ 'r' , 's' ]} ];
sal = [ {num:"2",amount:"1500"},{num:"1",amount:"700"} ];
t = {Class:"1", subMeds:subMed, numOfSub:1, sals:sal };
infoAcademic.push(t);
var tempObj = infoAcademic[1]; // an object
var mediumSubjects = tempObj["subMeds"]; // an array
console.log(mediumSubjects);
for(i=0;i<mediumSubjects.length;i++){
var temp = {}; // object
temp = mediumSubjects[i];
if(temp["med"] == 'bm'){
tempObj["numOfSub"] = tempObj["numOfSub"] - temp["sub"].length;
var salArr = tempObj["sals"]; // array
var j = salArr.length;
if(salArr.length > 0){
while(j--){
var salObj = salArr[j]; // object
var howManySub = salObj["num"];
if(howManySub > tempObj["numOfSub"]){
salArr.splice(j,1);
}
}
}
console.log("removing from the medSubjects list: ");
console.log(temp);
var removed = mediumSubjects.splice(i, 1);
break;
}
}
console.log("removed element: ");
console.log(removed);
console.log(mediumSubjects);
When I write this code this an online js editor https://js.do/ , the code gives result as per expected. But when I incorporate this code in a onclick function of my JSP page, no element gets removed from the mediumSubjects array. The removed element shows empty.
However, when I comment out this portion:
tempObj["numOfSubj"] = tempObj["numOfSub"] - temp["sub"].length;
var salArr = tempObj["sals"]; // array
var j = salArr.length;
if(salArr.length > 0){
while(j--){
var salObj = salArr[j]; // object
var howManySub = salObj["num"];
if(howManySub > tempObj["numOfSub"]){
salArr.splice(j,1);
}
}
}
the code surprisingly behaves as expected- it removes the element from the mediumSubjects array.
Is there any synchronization issue or something else? Why this sort of unusual behavior?
N.B. I need to remove elements from the array mediumSubjects, so delete won't work here.
Try this variant:
var newMedSub = medSub.filter(function(elem) {
return elem.med !== 'em';
});
It will help you to get a new array without unnessessary object.
All you actually need is to iterate over the outer array and in the body of this loop you need to iterate over the object keys.
for Example:
// removing med key from the array.
medSub.forEach(obj => {
for (let key in obj) {
if (key === 'med' && obj[key] === 'em') {
delete obj[key];
}
}
});
I hope this helps.

How To Get Multiple Array Value Based On Another Array In Javascript

I don't know what must be title for my question, I think it's so complicated. So, I have A array:
["87080207", "87101133", "91140156"]
And B Array:
["97150575", "97150575", "90141063"]
This B array, I put on html select value. Each of them(A and B array) is related. I need to show 87080207,87101133 (A array) when I choose value 97150575 (B array).
I have tried, but it didn't work.This is my code:
var a=[];
var b=[];
var arrayLength = dataComponentValuation.length;
for (var i = 0; i < arrayLength; i++) {
a.push(dataComponentValuation[i].valuated);
b.push(dataComponentValuation[i].valuator);
}
var ajoin = a.join();
var bjoin = b.join();
$('#valuatedEmpCompId_before').val(ajoin);
$('#valuator_before').val(bjoin);
In select, I put a function, this is it:
function emptyValuated() {
var valby = $("#valBy").val(); //chosen value from select
var b_valby = $("#valuator_before").val();
var b_valuated = $("#valuatedEmpCompId_before").val();
if(b_valby != ''){
if(valby != b_valby)
{
$("#valuatedEmpCompId").val('');
}
else{
$("#valuatedEmpCompId").val(b_valuated);
}
}
else{
$("#valuator_before").val(valby);
$("#valuatedEmpCompId").val(b_valuated);
}
}
Help me please...
As suggested, you could use an object as reference to the values of array A.
var arrayA = ["87080207", "87101133", "91140156"],
arrayB = ["97150575", "97150575", "90141063"],
object = Object.create(null);
arrayB.forEach(function (b, i) {
object[b] = object[b] || [];
object[b].push(arrayA[i]);
});
console.log(object);
I guess nowadays the Map object is a perfect solution for these jobs.
var arrayA = ["87080207", "87101133", "91140156"],
arrayB = ["97150575", "97150575", "90141063"],
myMap = arrayB.reduce((p,c,i) => p.has(c) ? p.set(c, p.get(c).concat(arrayA[i]))
: p.set(c,[arrayA[i]])
, new Map());
console.log(myMap.get("97150575"));
console.log(myMap.get("90141063"));

Replace key in an array of object

I have an array of objects :
arrayOfObject = [{'key1': [1,2]} , {'key2': [1,2,3]} , {'key3': [1,2,4]}]
I have the name of the key I want to replace in my array :
var keyString = 'key1';
And I have the new name the key should take :
var newKey = 'newKey'
How to make my array this :
arrayOfObject = [{'newKey': [1,2]} , {'key2': [1,2,3]} , {'key3': [1,2,4]}]
JavaScript: Object Rename Key this can help me to rename the key but the thing is how to access the object first in my array that has the key1 key.
Note that keyString is random. So it's pointless to get it like arrayOfObject[0]
https://jsfiddle.net/tcatsx6e/
Check this solution:
var arrayOfObject = [{'key1': [1,2]} , {'key2': [1,2,3]} , {'key3': [1,2,4]}];
var keyString = 'key1';
var newKey = 'newKey';
var newArray = arrayOfObject.map(function(item) {
if (keyString in item) {
var mem = item[keyString];
delete item[keyString];
item[newKey] = mem;
}
});
Please check this jsbin for a complete example.
This will return the index of the object you want to modify.
function(arr, keyString) {
for (var i = 0; i < arr.length; ++i) {
if (arr[i][keyString] !== undefined) {
return i;
}
}
}

array object manipulation to create new object

var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var expect = [
{month:"JAN",val: {"UK":"24","AUSTRIA":"64","ITALY":"21"}},
{month:"FEB",val: {"UK":"14","AUSTRIA":"24","ITALY":"22"}},
{month:"MAR",val: {"UK":"56","AUSTRIA":"24","ITALY":"51"}}
];
I have array of objects which i need to reshape for one other work. need some manipulation which will convert by one function. I have created plunker https://jsbin.com/himawakaju/edit?html,js,console,output
Main factors are Month, Country and its "AC" value.
Loop through, make an object and than loop through to make your array
var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var outTemp = {};
actual.forEach(function(obj){ //loop through array
//see if we saw the month already, if not create it
if(!outTemp[obj.month]) outTemp[obj.month] = { month : obj.month, val: {} };
outTemp[obj.month].val[obj.country] = obj.AC; //add the country with value
});
var expected = []; //convert the object to the array format that was expected
for (var p in outTemp) {
expected.push(outTemp[p]);
}
console.log(expected);
Iterate through array and create new list
var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var newList =[], val;
for(var i=0; i < actual.length; i+=3){
val = {};
val[actual[i].country] = actual[i]["AC"];
val[actual[i+1].country] = actual[i+1]["AC"];
val[actual[i+2].country] = actual[i+2]["AC"];
newList.push({month: actual[i].month, val:val})
}
document.body.innerHTML = JSON.stringify(newList);
This is the correct code... as above solution will help you if there are 3 rows and these will be in same sequnece.
Here is perfect solution :
var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var tmpArray = [];
var obj =[];
for(var k=0; k<actual.length; k++){
var position = tmpArray.indexOf(actual[k].month);
if(position == -1){
tmpArray.push(actual[k].month);
val = {};
for(var i=0; i<actual.length; i++){
if(actual[i].month == actual[k].month){
val[actual[i].country] = actual[i]["AC"];
}
}
obj.push({month: actual[k].month, val:val});
}
}

Categories

Resources