How to convert JSON Object into Javascript array - javascript

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"
}

Related

How to resolve error: "undefined" when reading single values from JSON using JavaScript?

I have a JavaScript function that outputs all values from a JSON file to a Terminal, but when attempting to print a single value, I get the following error: Line 74 - Cannot read properties of undefined (reading 'width')
Here is the code:
var json = `{
"columns": [{
"fname": "John",
"lname": "Doe",
"age": "23"
},
{
"fname": "Jane",
"lname": "Doe",
"age": ""
},
{
"fname": "Tom",
"lname": "Johns",
"age": ""
},
{
"fname": "Brian",
"lname": "Wicks",
"age": "27"
},
{
"fname": "Tim",
"lname": "Stone",
"age": ""
},
{
"fname": "Fred",
"lname": "Wilson",
"age": ""
},
{
"fname": "Jason",
"lname": "Voorhees",
"age": "90"
}
],
"rows": [{
"data": {
"width": "2",
"height": "7",
"length": "",
"finalresult": "44",
"firstresult": "",
"secondresult": "300.00",
"thirdresult": "700.40"
}
}]
}`;
var obj = JSON.parse(json);
function printValues(obj) {
for(var k in obj) {
if(obj[k] instanceof Object) {
printValues(obj[k]);
} else {
console.log(obj[k] + "\n");
};
}
};
// Printing all the values from the resulting object
printValues(obj);
//print single value
//console.log(obj["columns"]["rows"]["data"]["width"] + "\n");
console.log("Print Indiviual values:");
console.log(obj["rows"]["data"]["width"] + "\n"); //The Error
...Could I get some assistance as to what I'm doing wrong? ...Thanks
As #Yarin and #codemonkey pointed out—you're trying to access the data object as a direct object property of rows, e.g. obj.rows.data which is wrong and will return undefined because data is not a property of the rows object. Instead it's the first (and only) entry in the array of objects that is rows.
You need to either change the syntax to:
obj.rows[0].data.width
Or take the data object out of the array and remove the array so that the rows object is structured like this:
const obj = {
rows: {
data: {
width: 1
}
}
}
// Then you can use this syntax...
console.log( obj.rows.data.width )
// or even this syntax if you want to...
console.log( obj['rows']['data']['width'] )
I see that the width is the property of object data that is inside array rows...

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.

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);

Sorting data in MemoryStore (or any arbitrary data array)

Does Dojo hat any utilities for sotring the data within MemoryStore, or optionally, within any data collection?
I'd need all data from the MemoryStore, but sorted by single evt. more columns. Something like Collections.sort in Java...
I'd expect Store to have sort function, but I couldn't find anything in the documentation.
The dojo/store API allows sorting data at query time only, as far as I know. For example:
var store = new Memory({
data: [{
"firstName": "Bird",
"name": "Schultz"
}, {
"firstName": "Brittany",
"name": "Berg"
}, {
"firstName": "Haley",
"name": "Good"
}, {
"firstName": "Randolph",
"name": "Phillips"
}, {
"firstName": "Bernard",
"name": "Small"
}, {
"firstName": "Leslie",
"name": "Wynn"
}, {
"firstName": "Mercado",
"name": "Singleton"
}, {
"firstName": "Esmeralda",
"name": "Huber"
}, {
"firstName": "Juanita",
"name": "Saunders"
}, {
"firstName": "Beverly",
"name": "Clemons"
}]
});
console.log("Alphabetically by first name:");
store.query({}, {
sort: [{
attribute: "firstName",
descending: false
}]
}).forEach(function(person) {
console.log(person.firstName + " " + person.name);
});
You can provide multiple sort attributes as well.
Full example can be found on JSFiddle: http://jsfiddle.net/9HtT3/
When we sort our Data, we do this actual before the Items are stored. We take the filtered Values that are saved in an array and use array.sort()and called inside a function SortByName or SortByNumbers
looks like this:
function streetsToCombobox(results){
var adress;
var values = [];
var testVals={};
var features = results.features;
require(["dojo/_base/array","dojo/store/Memory","dijit/registry","dojo/domReady!"], function(array,Memory,registry){
if (!features[0]) {
alert(noDataFound);
}
else {
array.forEach(features, function(feature, i){
adress = feature.attributes.STRASSE;
if (!testVals[adress]) {
testVals[adress] = true;
values.push({
name: adress
});
}
});
values.sort(SortByName);
var dataItems = {
identifier: 'name',
label: 'name',
items: values
};
storeStreet = new Memory({
data: dataItems
});
//fill existing Combobox ID,NAME,VALUE,SEARCHATTR,ONCHANGE,STORENAME,COMBOBOX
fillExistingCombobox(
"adrSearchSelectCB",
"adrSearchSelectCBName",
"",
"name",
getAdresses,
storeStreet,
registry.byId("adrSearchSelectCBId")
);
}
});
}
function SortByName(x,y) {
return ((x.name == y.name) ? 0 : ((x.name > y.name) ? 1 : -1 ));
}
Maybe this brings some Ideas to you how to solve your Question.
Regards, Miriam

How to transform JavaScript hashmap?

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.

Categories

Resources