Convert json multidimensional to array javascript - javascript

I would like to convert Json data to an array Javascript, that I can access like using array[0][0], someone can help me please.
[
{
"Login": "test1",
"Nom": "test1",
"Prenom": "test1p",
"password": "124564",
"Email": "test1#gmail.com"
},
{
"Login": "test2",
"Nom": "test2",
"Prenom": "test2p",
"password": "124564",
"Email": "test2#gmail.com"
}
]
I tried this piece of code but nothing happen , I can't access to a specific(Exemple I would like to have Nom) data in array using for example array[0][1].
Code.js
var data = [
{
"Login": "test1",
"Nom": "test1",
"Prenom": "test1p",
"password": "1267846",
"Email": "test1#gmail.com"
},
{
"Login": "test2",
"Nom": "test2",
"Prenom": "test2p",
"password": "124494",
"Email": "test2#gmail.com"
}
];
function data_to_array(data) {
var array = [];
for (var key in data) {
var value = data[key];
if (typeof value === 'string') {
array[key] = value;
} else {
array[key] = data_to_array(value);
}
}
return array;
}
var array = data_to_array(data);
for(var i in array)
console.log(array[i]);
Once parsed, if I try to access it using myArr[0][1], it shows as undefined.

var arr = [];
for (var i=0, len=data.length, tmp; i<len; i++) {
tmp = [];
for (var k in data[i]) {
if (data[i].hasOwnProperty(k)) {
tmp.push(data[i][k]);
}
}
arr.push(tmp);
}
arr;
// [
// ["test1","test1","test1p","124564","test1#gmail.com"],
// ["test2","test2","test2p","124564","test2#gmail.com"]
// ]
If you can rely on es5 functions, you can use Array.prototype.map and Object.keys
var arr = data.map(function(e) {
return Object.keys(e).map(function(k) { return e[k]; });
});
arr;
// [
// ["test1","test1","test1p","124564","test1#gmail.com"],
// ["test2","test2","test2p","124564","test2#gmail.com"]
// ]

you have confused with the array and objects. All arrays are objects. but not all objects are arrays. You use "for..in" loop in wrong understanding on array containing objects.
If you add more console statements and check, you can understand how it works. Let me give reqd. solution for your scenario.
var data = [
{
"Login": "test1",
"Nom": "test1",
"Prenom": "test1p",
"password": "1267846",
"Email": "test1#gmail.com"
},
{
"Login": "test2",
"Nom": "test2",
"Prenom": "test2p",
"password": "124494",
"Email": "test2#gmail.com"
}
];
function data_to_array(data) {
var array = [];
for (var i=0;i<data.length;i++) {
var obj = data[i];
array[i] = new Array();
for(var key in obj) {
array[i].push(obj[key]);
}
}
return array;
}
var array = data_to_array(data);
console.log(array);

Related

javascript: All device data is read into the object

When I write Javascript, I want to read all the data of the device into the object, but only the last one is read.
I would like to ask how I can read all the data in the device into obj, thank you.
let data = [
{
"bind": "82218018295591013",
"account": "admin",
"password": "0000",
"devices": [
{
"ip": "192.168.0.88",
"brand_name": "UNIVIEW",
"name": "UNIVIEW"
}
]
},
{
"bind": "94907378021478863",
"account": "admin",
"password": "0000",
"devices": [
{
"ip": "192.168.0.88",
"brand_name": "UNIVIEW",
"name": "UNIVIEW"
},
{
"ip": "192.168.0.89",
"brand_name": "hisharp",
"name": "hisharp"
}
]
}
]
let obj = {};
function getObj() {
for (let i = 0; i < data.length; i++) {
for (let j = 0; j < data[i].devices.length; j++) {
obj.devices = data[i].devices[j];
}
}
return obj;
}
console.log('obj :>> ', obj);
getObj();
You are having a single object for all objects and you store all objects, but the problem is that each time that you store an object, you are overriding the previous one with it.
function getObj(obj) {
obj.devices = [];
for (let i = 0; i < data.length; i++) {
obj.devices.concat(data[i].devices);
}
return obj;
}
and pass obj:
getObj(obj);
console.log('obj :>> ', obj);

Having trouble using GroupBy with lodash trying to format my array correctly

I want to take a list of users and categorize them in a new array to be rendered by my app.
What I am given:
OnlineList = [
{
"Role": "Adjuster",
"AccountId": "4",
"UserId": "1e72d58e",
"DisplayName": "Big Bob",
},
{
"Role": "Adviser",
"AccountId": "5",
"UserId": "a0daba73",
"DisplayName": "Sassy Sally",
}
];
What result I want:
OnlineUsers = {
"Dealership": [
{
"Role": "Adviser",
"AccountId": "Dealership",
"UserId": "a0daba73",
"DisplayName": "Sassy Sally",
}
],
"ClaimsCo": [
{
"Role": "Adjuster",
"AccountId": "ClaimsCo",
"UserId": "1e72d58e",
"DisplayName": "Big Bob",
}
]
}
Result I get:
OnlineUsers = {
"5": [ <----------- Problem
{
"Role": "Adviser",
"AccountId": "5", <----------- Problem
"UserId": "a0daba73",
"DisplayName": "Sassy Sally",
}
],
"ClaimsCo": [
{
"Role": "Adjuster",
"AccountId": "Dealership",
"UserId": "1e72d58e",
"DisplayName": "Big Bob",
}
]
}
Here is a JFiddle I set up replicating the problem: http://jsfiddle.net/vc4mjwx3/20/
My code:
// loaded from API Request into array
var OnlineList = [];
// Sorted and ordered for display
var OnlineUsers = [];
OnlineList = [
{
"Role": "Adjuster",
"AccountId": "4",
"UserId": "1e72d58e",
"DisplayName": "Big Bob",
},
{
"Role": "Adviser",
"AccountId": "5",
"UserId": "a0daba73",
"DisplayName": "Sassy Sally",
}
];
// GroupBy function: https://stackoverflow.com/questions/14446511/most-efficient-method-to-groupby-on-an-array-of-objects/43215522
let groupBy = function(xs, key) {
return xs.reduce(function(rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
// Simulates a get by Id API service
let accountService = (id) => {
if (id == 4) {
return "ClaimsCo."
}
else {
return "Dealership"
}
}
// pass in AccountId
let getAccountName = function(int) {
var accountName = "";
//get AccountName from Id
accountName = accountService(int);
for(var x=0; x < OnlineList.length; x++){
// check for AccountId
if(OnlineList[x].hasOwnProperty('AccountId')){
// Set AccountId value to AccountName
OnlineList[x].AccountId = accountName;
// Group results and set to OnlineUsers array
OnlineUsers = groupBy(OnlineList, 'AccountId');
break;
}
}
};
// Go into first element of array and get AccountId value
var id = _.get(OnlineList[0], "AccountId");
// Convert value to int
var int = parseInt(id,10);
// Pass into function that gets AccountName from AccountId and replaces AccountId in that element of OnlineList array
getAccountName(int);
//result
console.log(OnlineUsers);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
Overall I want my code to function like this:
Iterate over each element in the OnlineList
For that element, grab the AccountId value
Pass that AccountId value into a service that will return an AccountName
Replace the AccountId of that element with the AccountName
repeat for all other elements in OnlineList array
After all AccountId/AccountName are handled, use GroupBy to group all elements of the OnlineList array by AccountId property and set them to a new array called OnlineUsers.
The question has been answered but I have a different solution I would like to share.
I recently created a library that does array categorization in JavaScript, called categorize.
Here is what would be the solution using it:
const { categorize } = require("categorize");
const onlineList = [
{
"Role": "Adjuster",
"AccountId": "4",
"UserId": "1e72d58e",
"DisplayName": "Big Bob",
},
{
"Role": "Adviser",
"AccountId": "5",
"UserId": "a0daba73",
"DisplayName": "Sassy Sally",
}
];
const categories = [
{ name: "Dealership", filter: ({ AccountId }) => AccountId === "4" },
{ name: "ClaimsCo", filter: ({ AccountId }) => AccountId === "5" },
];
const onlineUsers = categorize(onlineList, categories);
The onlineUsers variable will contain this object:
{
"Dealership": [
{
"Role": "Adjuster",
"AccountId": "4",
"UserId": "1e72d58e",
"DisplayName": "Big Bob"
}
],
"ClaimsCo": [
{
"Role": "Adviser",
"AccountId": "5",
"UserId": "a0daba73",
"DisplayName": "Sassy Sally"
}
]
}
// loaded from API Request into array
var OnlineList = [];
// Sorted and ordered for display
var OnlineUsers = [];
OnlineList = [{
"Role": "Adjuster",
"AccountId": "4",
"UserId": "1e72d58e",
"DisplayName": "Big Bob",
},
{
"Role": "Adviser",
"AccountId": "5",
"UserId": "a0daba73",
"DisplayName": "Sassy Sally",
}
];
// GroupBy function: https://stackoverflow.com/questions/14446511/most-efficient-method-to-groupby-on-an-array-of-objects/43215522
let groupBy = function(xs, key) {
return xs.reduce(function(rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
// Simulates a get by Id API service
let accountService = (id) => {
if (id == 4) {
return "ClaimsCo."
} else {
return "Dealership"
}
}
// pass in AccountId
let getAccountName = function(int, element) {
var accountName = "";
//get AccountName from Id
accountName = accountService(int);
// check for AccountId
if (OnlineList[element].hasOwnProperty('AccountId')) {
// Set AccountId value to AccountName
OnlineList[element].AccountId = accountName;
// Group results and set to OnlineUsers array
OnlineUsers = groupBy(OnlineList, 'AccountId');
}
};
for (var x = 0; x < OnlineList.length; x++) {
var id = _.get(OnlineList[x], "AccountId");
var int = parseInt(id, 10);
getAccountName(int, x);
}
// Go into first element of array and get AccountId value
//result
console.log(OnlineUsers);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
I had to pass the count from my for loop into my getAccountName function. Now it works as it should. Hope this helps somebody.
You need to map and replace AccountId number with the name, and then group by the name. I use _.flow() to create a pipeline:
const { flow, partialRight: pr, map, groupBy } = _;
// Simulates a get by Id API service
const accountService = (id) => id === 4 ? "ClaimsCo." : "Dealership";
const fn = flow(
pr(map, o => ({ ...o, AccountId: accountService(+o.AccountId) })), // replace AccountId with name the + operator converts to number
pr(groupBy, 'AccountId'), // group by the new AccountId
)
const OnlineList = [{"Role":"Adjuster","AccountId":"4","UserId":"1e72d58e","DisplayName":"Big Bob"},{"Role":"Adviser","AccountId":"5","UserId":"a0daba73","DisplayName":"Sassy Sally"}];
//result
const OnlineUsers = fn(OnlineList);
console.log(OnlineUsers);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
And the terser version using lodash/fp:
const { flow, map, groupBy } = _;
// Simulates a get by Id API service
const accountService = (id) => id === 4 ? "ClaimsCo." : "Dealership";
const fn = flow(
map(o => ({ ...o, AccountId: accountService(+o.AccountId) })), // replace AccountId with name the + operator converts to number
groupBy('AccountId'), // group by the new AccountId
)
const OnlineList = [{"Role":"Adjuster","AccountId":"4","UserId":"1e72d58e","DisplayName":"Big Bob"},{"Role":"Adviser","AccountId":"5","UserId":"a0daba73","DisplayName":"Sassy Sally"}];
//result
const OnlineUsers = fn(OnlineList);
console.log(OnlineUsers);
<script src='https://cdn.jsdelivr.net/g/lodash#4(lodash.min.js+lodash.fp.min.js)'></script>

JavaScript converting an object to an array

I've researched for about a day and haven't had any luck. I'm trying to access the object properties to simply add it to a typed class in JavaScript. How can i accomplish this? This is the object im receiving:
And this my code resulting in the following error:
Object.keys(selected).forEach(function (key) {
console.log(selected[key]);
});
Error:
ERROR TypeError: Cannot convert undefined or null to object
Any help is most appreciated as I've come to here as a last resort.
selected looks like this:
Object.keys(selected)... the selected in json string:
{
"selected": [
{
"Id": 4,
"Type": 0,
"Image": "",
"Name": "TestName",
"Roles": "TestRole",
"Facility": "TestFacil"
}
]
}
The variable selected is an array, you can try this:
selected.forEach(
item=>
Object.keys(item).forEach(function (key) {
console.log(item[key]);
})
)
It could also be:
selected.selected.forEach(
In your question it's not clear what the name is of the value you are logging the json string of.
let data = {
"selected": [
{
"Id": 4,
"Type": 0,
"Image": "",
"Name": "TestName",
"Roles": "TestRole",
"Facility": "TestFacil"
}
]
}
let arr = [];
for (var key in data) {
arr.push(data[key]);
}
console.log(arr)
or you can use that if you wanna convert the whole object to arrays of arrays
let data = {
"selected": [
{
"Id": 4,
"Type": 0,
"Image": "",
"Name": "TestName",
"Roles": "TestRole",
"Facility": "TestFacil"
}
]
}
var arr = [];
var i =0;
for( var key in data){
var innerArr = [key];
arr.push(innerArr)
for(var values in data[key]){
for(var keys in data[key][values]){
var innerArr3 = [keys];
innerArr.push(innerArr3)
innerArr3.push(data[key][values][keys])
}
}
}
console.log(arr)

How to iterate nested json object?

I have a nested JSON Object and i want to iterate that.
JSON Response
{
"specifications": {
"IP6": {
"name": "Devices",
"productSubType": "Device",
"productSpecificationType": "Phones"
}
},
"offers": {
"US-PRE-IPHONE-CASE": {
"path": "productDetails/IP6",
"familyData": {
"0": "Missing Family Level data Should be here"
},
"facets": [],
"type": [],
"offers": {
"US-PRE-HG-PH-IP6": {
"hashDigest": "cf23df2207d99a74fbe169e3eba035e633b65d94",
"offerName": "offerNameString",
"productName": "iPhone 6 Case Mate Naked Tough Case - Clear",
"productOfferings": {
"ratings": "4.5",
"noOfReviews": "2010"
},
"offerStatus": {},
"displayPriority": "100200",
"descriptions": {
"shortDescription": "Iphone Decription ",
"longDescription": "longDescriptionStri6 descriptionng",
"alternativeDescription": "alternativeDescriptionString",
"reprsentativeDescription": ""
},
"specifications": [
"someSpecificationId1"
],
"brand": "Apple",
"productType": "Device",
"productSubType": "Phone",
"offerType": "",
"offerSubType": "",
"compatibility": {},
"classification": [],
"images": {
"thumbanail": {
"imagePath": "http://s.tmocache.com/images/png/products/accessories/SUPM43270/SUPM43270-small.png"
}
},
"equipmentCharacteristics": {},
"offerVariants": {},
"type": "hard-good",
"offers": [],
"family": "IP6",
"pricePoints": {
"withServicePrice16GBNEW": {
"displayPriority": "1001",
"pricingMessage": "device price with service activation",
"price": "34.99",
"discounts": {}
}
},
"dynamicPricingData": {},
"inventoryData": {
"SKUGOLD16GBN": {
"availibility": "Pre-order now!",
"availableTimeline": ""
}
}
}
}
}
}
}
Now as you see there are nested JSON objects in this and I want the value of
productName
shortDescription
imagePath
availibility
What I have tried is
function change(){
var acc = response; //response is JSON Object mentioned above
var accArray = [];
var accArray1 = [];
for (var obj in acc.specifications){
accArray.push(obj);
}
alert(accArray[0]);
for (var obj in accArray[0].offers){
accArray1.push(obj);
}
alert(accArray1[0]);
}
I am able to get the first object the first alert output is
IP6
but when I am trying to iterarte the IP6 object in same way the output is
undefined
I want to fetch all the 4 values as I mentioned above and then put them in an array.
As Grundy pointed out in his comment, obj in your code is the key of properties/items in specifications object. That means 'obj' is just a string.
To get reference to the object, change your code as below:
for(var obj in acc.specifications){
accArray.push(acc.specifications[obj]);
}
For better readability change obj to key
You can use for..in loop and recursion.
function find(obj, fieldName){
if(Array.isArray(obj)){
for(var i=0, len=obj.length;i<len;i++){
var nested = find(obj[i],fieldName);
if(nested.isFind) return nested;
}
}else{
if(typeof obj !== "object") return {isFind:false};
for(var i in obj){
if(i === fieldName) return {isFind:true, value:obj[i]};
var nested = find(obj[i],fieldName);
if(nested.isFind) return nested;
}
}
return {isFind:false};
}
this function return object with field isFind for case when available value can be null or undefined
var obj = {
"specifications": {
"IP6": {
"name": "Devices",
"productSubType": "Device",
"productSpecificationType": "Phones"
}
},
"offers": {
"US-PRE-IPHONE-CASE": {
"path": "productDetails/IP6",
"familyData": {
"0": "Missing Family Level data Should be here"
},
"facets": [],
"type": [],
"offers": {
"US-PRE-HG-PH-IP6": {
"hashDigest": "cf23df2207d99a74fbe169e3eba035e633b65d94",
"offerName": "offerNameString",
"productName": "iPhone 6 Case Mate Naked Tough Case - Clear",
"productOfferings": {
"ratings": "4.5",
"noOfReviews": "2010"
},
"offerStatus": {},
"displayPriority": "100200",
"descriptions": {
"shortDescription": "Iphone Decription ",
"longDescription": "longDescriptionStri6 descriptionng",
"alternativeDescription": "alternativeDescriptionString",
"reprsentativeDescription": ""
},
"specifications": [
"someSpecificationId1"
],
"brand": "Apple",
"productType": "Device",
"productSubType": "Phone",
"offerType": "",
"offerSubType": "",
"compatibility": {},
"classification": [],
"images": {
"thumbanail": {
"imagePath": "http://s.tmocache.com/images/png/products/accessories/SUPM43270/SUPM43270-small.png"
}
},
"equipmentCharacteristics": {},
"offerVariants": {},
"type": "hard-good",
"offers": [],
"family": "IP6",
"pricePoints": {
"withServicePrice16GBNEW": {
"displayPriority": "1001",
"pricingMessage": "device price with service activation",
"price": "34.99",
"discounts": {}
}
},
"dynamicPricingData": {},
"inventoryData": {
"SKUGOLD16GBN": {
"availibility": "Pre-order now!",
"availableTimeline": ""
}
}
}
}
}
}
}
function find(obj, fieldName){
if(Array.isArray(obj)){
for(var i=0, len=obj.length;i<len;i++){
var nested = find(obj[i],fieldName);
if(nested.isFind) return nested;
}
}else{
if(typeof obj !== "object") return {isFind:false};
for(var i in obj){
if(i === fieldName) return {isFind:true, value:obj[i]};
var nested = find(obj[i],fieldName);
if(nested.isFind) return nested;
}
}
return {isFind:false};
}
var result = ['productName','shortDescription','imagePath','availibility'].map(function(el){ return find(obj,el).value});
document.getElementById('r').innerHTML = JSON.stringify(result,null,2);
<pre id='r'></pre>
Your json code is a complex data binding structure. It same like c# complex data binding. So you need to call the obj by through it call name.
for eg:
var data = {"ex":{"a":{"a1":"a1","a2":"a2"},"b":{"b1":"b1","b2":"b2"}}}
so data is a class and it includes "ex" object
data returns =>Object {ex: Object}
if you need to access "a" or "b" object means , you need to access through the"ex" object.
for eg:
data.ex.a => Object {a1: "a1", a2: "a2"}
in your code
for(var obj in acc.specifications){
accArray.push(obj);
}
obj only push 1st element of acc.sppectification object.
So please try this.
foreach(var obj acc.specification){
arr1.push(acc.specification[obj])
}
foreach (var obj acc.offers){
arr2.push(acc.offers[obj])
}

Creating and Updating JSON

I can create a Json object as here
How to create json by javascript for loop?
great!
and I have created one like below
[
{
"id": "10",
"userName": "kuttan"
},
{
"id": "11",
"userName": "kunjan"
}
]
Suppose I want to update name of the user with id 10 to "new name"
what should i do?(i dont know the index is 1)
Loop over your array of objects (because that's what it is), and check the "id" attribute of each object.
var list = [ { "id": "10", "userName": "kuttan" }, { "id": "11", "userName": "kunjan" } ];
for (var i=0;i<list.length;i++) {
if (list[i].id == "10") {
alert(i);
};
};
You could then abstract this into some nice function.
function findIndexById(list, id) {
for (var i=0;i<list.length;i++) {
if (list[i].id == id) {
return i;
};
};
return -1;
};
Then use it as follows:
var list = [ { "id": "10", "userName": "kuttan" }, { "id": "11", "userName": "kunjan" } ];
var index = findIndexById(list, "10");
if (index !== -1) {
list[index].userName = "new username";
};
You can loop through the array and check the id property of the object in the current iteration. If it's 10, assign the new username to userName.
var json = [ { "id": "10", "userName": "kuttan" }, { "id": "11", "userName": "kunjan" } ],
len = json.length,
obj;
while(len--) {
obj = json[len];
if (obj.id == 10) {
obj.userName = 'foobar';
}
}
console.log(json); // outputs [{id:"10", userName:"foobar"}, {id:"11", userName:"kunjan"}]

Categories