How to transform JavaScript hashmap? - javascript

i'm trying to create a <String, Array()> map from a json object.
Imagine i got this json structure:
[
{
"userId": "123123",
"password": "fafafa",
"age": "21"
},
{
"userId": "321321",
"password": "nana123",
"age": "34"
}
]
The map i want to create would be:
key (string), value (array)
{
"userId": [
"123123",
"321321"
],
"password": [
"fafafa",
"nana123"
],
"age": [
"21",
"34"
]
}
Is it possible to do this? :/
Thanks in advance.

Demo
var json = '[{"userId" : "123123", "password": "fafafa", "age": "21"}, {"userId" : "321321", "password" : "nana123", "age" : "34"}]';
var list = JSON.parse(json);
var output = {};
for(var i=0; i<list.length; i++)
{
for(var key in list[i])
{
if(list[i].hasOwnProperty(key))
{
if(typeof output[key] == 'undefined')
{
output[key] = [];
}
output[key].push(list[i][key]);
}
}
}
document.write(JSON.stringify(output));
Outputs:
{"userId":["123123","321321"],"password":["fafafa","nana123"],"age":["21","34"]}

function mergeAttributes(arr) {
return arr.reduce(function(memo, obj) { // For each object in the input array.
Object.keys(obj).forEach(function(key) { // For each key in the object.
if (!(key in memo)) { memo[key] = []; } // Create an array the first time.
memo[key].push(obj[key]); // Add this property to the reduced object.
});
return memo;
}, {});
}
var json = '[{"userId" : "123123", "password": "fafafa", "age": "21"}, {"userId" : "321321", "password" : "nana123", "age" : "34"}]';
mergeAttributes(JSON.parse(json));
// {
// "userId": ["123123", "321321"],
// "password": ["fafafa", "nana123"],
// "age": ["21", "34"]
// }

Javascript's JSON.stringify will help you to convert any JSON compliant object model into a JSON string.

Related

Create json object dynamic in nodejs

I have json :
{
"fullName": "abc",
"age": 19,
...
}
I want use Nodejs to add element in above json to object named Variables in below json
{
"variables": {
"fullName" : {
"value" : "abc",
"type" : "String"
},
"age": {
"value" : 19,
"type": "Number"
},
...
}
}
Please help me this case!
You can use Object.entries with .reduce()
let data = {
"fullName": "abc",
"age": 19,
}
let result = Object.entries(data).reduce((a, [key, value]) => {
a.variables[key] = { value, type: typeof value}
return a;
}, { variables: {}})
console.log(result);
We can first entries of that object and then map it accordingly after that we convert that object using Object.fromentries. Here is an implementation:
const obj = { "fullName": "abc", "age": 19 };
const result = Object.fromEntries(Object.entries(obj).map(([k,value])=>[k,{value, type:typeof value}]));
console.log({variable:result});
Are you looking for JSON.parse to get a struct from your file, then JSON.stringify to create a json from your struct ?

How to push values to an object from inside a map function when a condition is met?

How can we push values to an object from inside a map function and return that single object. I have string comparison condition inside the map function. I tried using Object.assign but it returns an array with multiple object inside that array. Instead of this multiple object I'm expecting a single object inside an array.
Map function
let arrayObj = arrayToTraverse.map(function(item) {
var myObj = {};
if(item.inputvalue === 'Name'){
Object.assign(myObj, {name: item.value});
} else if (item.inputvalue === 'Email'){
Object.assign(organizerInfo, {email: item.value});
} else if (item.inputvalue === 'Company'){
Object.assign(organizerInfo, {company: item.value});
}
return myObj;
});
console.log("The array object is", arrayObj)
This return the array of objects as follows
[
{
"name": "Tom"
},
{
"email": "tom#abc.com"
},
{
"company": "ABC"
}
]
But The array I'm expecting is
[
{
"name": "Tom",
"email": "tom#abc.com",
"company": "ABC"
}
]
// or
[
"returned": {
"name": "Tom",
"email": "tom#abc.com",
"company": "ABC"
}
]
An example of arrayToTraverse can be considered as following
[
{
"id": "1",
"inputvalue": "Name",
"value": "Tom",
"type": "Short Text"
},
{
"id": "2",
"inputvalue": "Email",
"value": "tom#abc.com",
"type": "Email ID"
},
{
"id": "3",
"inputvalue": "Company",
"value": "Google",
"type": "Long Text"
}
]
Simply put, you're trying to reduce an array to a single object, not map one array to another.
var arrayToTraverse = [
{inputvalue:"Name",value:"Tom"},
{inputvalue:"Email",value:"tom#abc.com"},
{inputvalue:"Company",value:"ABC"},
{inputvalue:"Foo",value:"Bar"} // wont show up
];
var valuesRequired = ["Name","Email","Company"];
var result = arrayToTraverse.reduce( (acc, item) => {
if(valuesRequired.includes(item.inputvalue))
acc[item.inputvalue.toLowerCase()] = item.value;
return acc;
}, {});
console.log(result);
Edit: Added lookup array for required fields.

Update a json key inside a json file using Javascript?

I have a JSON file, I need to read that JSON file and update a particular key with new values. How can I do it with the help of javascript in the typescript file?
datafile.json:
{
"Id": {
"place": {
"operations": [{
"Name": "John",
"Address": "USA"
}]
}
}
}
Now in my test.ts file
const filepath = 'c:/datafile.json';
var testjson = filepath.Id[place][operations][0];
var mykey = 'Address';
//testjson[mykey] = 'UK';
updateJsonFile(filepath, (data) => {
data[mykey] = 'UK';
console.log(data);
return data;
});
The issue is it update the JSON with new key and values as below:
{
"Id": {
"place": {
"operations": [{
"Name": "John",
"Address": "USA"
}]
}
"Address": "UK"
}
}
But I want to just change the value of a particular key then adding new keys. Is it possible in JS.?
data doesn't have an Address property, its operations, which is inside place.
If you try to set it like
data[mykey] = 'UK';
it will create a new property to data,
It should be
o.Id.place.operations[0][mykey] = 'UK';
jsonString = `
{
"Id": {
"place": {
"operations": [{
"Name": "John",
"Address": "USA"
}]
}
}
}
`;
let o = JSON.parse(jsonString);
var mykey = 'Address';
o.Id.place.operations[0][mykey] = 'UK';
console.dir(o);

Create arrays from JavaScript objects

I have some data which looks like this:
{
"obj":
[
{
"name": "name1",
"age": "24"
},
{
"name": "name2",
"age": "17"
}
]
}
What I need to do is to create 2 arrays from it.
For example:
namelist[];
agelist[];
so the result would be:
namelist: ['name1', 'name2'];
agelist: [24, 17];
My question is, how can I do this?
var namelist = [];
var agelist = [];
for(var i in obj.obj){
namelist.push(obj.obj[i].name);
agelist.push(obj.obj[i].age);
}
console.log(namelist, agelist);
Is this what U wanted ?
var zz={
"obj": [
{
"name": "name1",
"age": "24"
},
{
"name": "name2",
"age": "17"
}
]
}
namelist=[];
agelist=[];
zz.obj.forEach(function(rec){
namelist.push(rec.name);
agelist.push(rec.age);
})
console.log(namelist,agelist)
You could use this ES6 code, and use the unitary plus for getting the ages as numbers. Assuming your object is stored in variable data:
var namelist = data.obj.map( o => o.name );
var agelist = data.obj.map( o => +o.age );
var data = {
"obj": [
{
"name": "name1",
"age": "24"
},
{
"name": "name2",
"age": "17"
}
]
};
var namelist = data.obj.map( o => o.name );
var agelist = data.obj.map( o => +o.age );
console.log(namelist);
console.log(agelist);
var arr = $.map(myObj, function(value, index) {
return [value];
});
console.log(arr);
if you are not using Jquery then:
var arr = Object.keys(myObj).map(function (key)
{ return obj[key];
});`
Make use of jquery map function or otherwise you can loop over the object and push it into array using javascript for loop and use the push() function. Refer Loop through an array in JavaScript
Jquery
var data = {
"obj": [
{
"name": "name1",
"age": "24"
},
{
"name": "name2",
"age": "17"
}
]
}
var name = $.map(data.obj, function(value, index) {
return value.name;
});
var age = $.map(data.obj, function(value, index) {
return value.age;
});
console.log(name);
console.log(age);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Javascript
var data = {
"obj": [
{
"name": "name1",
"age": "24"
},
{
"name": "name2",
"age": "17"
}
]
}
var names = [], ages=[];
data.obj.forEach(function(value, index) {
names.push(value.name);
ages.push(value.age);
});
console.log(names,ages);

How to convert JSON Object into Javascript array

Linked to this question and this one also, I would like to know how to do the exact same thing but with a different type of JSON :
Here my JSON Object :
var myDb = {
"04c85ccab52880": {
"name": "name1",
"firstname": "fname1",
"societe": "soc1"
},
"04c95ccab52880": {
"name": "name2",
"firstname": "fname2",
"societe": "soc2"
},
"048574220e2a80": {
"name": "name3",
"firstname": "fname3",
"societe": "soc3"
}
};
My problem is that my JSON is different from their JSON, actually I have an array of array in mine. So how to convert this into a Javascript array ?
var arr = [];
$.each( myDb, function( key, value ) {
arr.push( value );
});
console.log(user_list);
This kind of script seems to return my 3 different objects but where are my uid from JSON ? How can I get them ? Because now my keys are 0,1,2 and no longer my uid.
Any ideas ? Thanks
A working JSFIDDLE
JS code:
//var arr = [];
var myDb = {
"04c85ccab52880": {
"name": "name1",
"firstname": "fname1",
"societe": "soc1"
},
"04c95ccab52880": {
"name": "name2",
"firstname": "fname2",
"societe": "soc2"
},
"048574220e2a80": {
"name": "name3",
"firstname": "fname3",
"societe": "soc3"
}
};
$.each( myDb, function( key, value ) {
//arr.push( value );
console.log("key => "+key);//will output: 04c85ccab52880 and all such
$.each( value, function( ky, val ) {
console.log('ky => '+ky);//will output: name, firstname, societe
console.log('val => '+val);//will output: name1, fname1, soc1
});
});
if you want to convert them, with key. I suggest something like below
var mapped = Object.keys( myDb ).map(function( uid ){
return (myDb[uid ].uid = uid ) && myDb[uid ];
});
for value in your array look like, example mapped[0] has value :
{
"name": "name1",
"firstname": "fname1",
"societe": "soc1",
"uid": "04c85ccab52880"
}

Categories

Resources