How to get specific data from object array? - javascript

I'm a beginner and would like to know how I can get a specific object from an array
I have an Array that looks like this:
data {
"orderid": 5,
"orderdate": "testurl.com",
"username": "chris",
"email": "",
"userinfo": [
{
"status": "processing",
"duedate": "" ,
}
]
},
To get the data from above I would do something like this:
return this.data.orderid
But how can I go deeper and get the status in userinfo?
return this.data.orderid.userinfo.status
doesn't work... anyone have any ideas?

A few points:
data is not an array, is an Object (see the curly braces, arrays have squared brackets). To be really precise, your syntax is invalid, but I assume you wanted to type data = { ... }, as opposed to data { ... }
Your syntax is almost correct, the only mistake you are making is that userinfo is an array, and arrays have numeric indexes (I.e. array[0], array[1]). What you are looking for is this.data.orderid.userinfo[0].status

Use data.userinfo[0].status to get the value (in your case this.data.userinfo[0].status)
var data = {
"orderid": 5,
"orderdate": "testurl.com",
"username": "chris",
"email": "",
"userinfo": [
{
"status": "processing",
"duedate": "" ,
}
]
};
console.log(data.userinfo[0].status);

User Info is an array, so you would need to access it using indexer like so:
return this.data.userinfo[0].status
MDN on arrays: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

You need to iterate over data.userinfo (it's an array)
var data = {
"orderid": 5,
"orderdate": "testurl.com",
"username": "chris",
"email": "",
"userinfo": [
{
"status": "processing",
"duedate": "" ,
}
]
};
data.userinfo.forEach(function(element) {
console.log(element.status);
});

Related

Typescript Filter and return single key

I have a set of checkboxes that allow a user to check which roles to assign to a new user. I am able to filter back and get only the checkboxes that are actually checked, however, I am having trouble finding the best way to just return the "name" key of those checked checkboxes.
userToAdd.roles = this.roles.filter( (role) => role.checked );
Is there a way to use a reduce, or basically just say "role.name" in the filter so I don't return the entire object? I can do this with a for loop, but I'm curious if there is a better way to just return the name key as part of the filter?
This is how the object looks now, which is wrong:
{
"firstName": "sfsdfds",
"username": "fdsfsdf",
"lastName": "sdfsdfsdf",
"email": "dsfsdfdsf",
"roles": [
{
"ID": "ce97fb46-7e04-4a4f-b393-5a5492b558fb",
"name": "admin",
"checked": true
},
{
"ID": "e89bacd2-4140-46a1-9a2b-0f85aa9f9ca0",
"name": "offline_access",
"checked": true
}
],
"password": "pass"
}
This is how the object should look, in the roles array i just include the name, not the ID or checked keys:
{
"firstName": "testing",
"lastName": "testing",
"username": "testing",
"email": "testing",
"roles": [
"uma_authorization",
"offline_access"
],
"password": "pass"
}
you could map after filtering. i.e:
userToAdd.roles = this.roles.filter( (role) => role.checked ).map(role => role.name;
You can achieve this using array map() method and object destructuring like:
userToAdd.roles = this.roles.filter(({checked}) => checked).map(({name}) => name);
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
Yes you can use reduce.
const data = {
"firstName": "sfsdfds",
"username": "fdsfsdf",
"lastName": "sdfsdfsdf",
"email": "dsfsdfdsf",
"roles": [
{
"ID": "ce97fb46-7e04-4a4f-b393-5a5492b558fb",
"name": "admin",
"checked": true
},
{
"ID": "e89bacd2-4140-46a1-9a2b-0f85aa9f9ca0",
"name": "offline_access",
"checked": true
},
{
"ID": "e89bacd2-4140-46a1-9a2b-0f85aa9f9ca0",
"name": "offline_access2",
"checked": false
}
],
"password": "pass"
}
let filtered = data.roles.reduce((acc, curr)=>{
if(curr.checked) {
acc.push({
name: curr.name
})
}
return acc;
}, []);
console.log(filtered);
.filter().map() would also works but with reduce you don't have to iterate over array twice.
If you have linq, this is another option:
userToAdd.roles = from(this.roles).where(role => role.checked ).select(role =>role.name).toArray();
You can also use this:
this.roles.filter( (role) => role.checked )[0].anyPropert;

How to join array objects with lodash

I have two variables with two different array objects. One is the collection(this.collection) object and the second is the user(this.user) object.
I want to join this two objects into one by the UID.
Here is the collection object:
{
"id":"d67de5QJ",
"admins":[
"494949393"
],
"color":"#029ae4",
"components":{
"forums":false,
"pages":true,
"photos":false,
"videos":false
},
"createdAt":"2018-02-09 14:38:59",
"description":"Angular is a TypeS",
"homepage":"pages",
"photoURL":"https://firebase..",
"status":"Public",
"title":"Angular 5",
"uid":"hlyAbEUfJhbxy",
"updatedAt":"2018-02-09 14:38:59"
}
And here is the user object
{
"bio": "<strong>PROFILE NEEDS EDITING",
"contactInfo": {
...
},
"createdAt": "2018-02-09 12:43:47",
,
"email": "email#gmail.com",
"avatar": "https://lh5.googleusercontent.com/-3LjYEmTIZlo/A...",
"roles": {
"admin": false,
"dealer": false,
"user": true
},
"status": "online",
"uid": "hlyAbEUfJhbxy",
"updatedAt": "2018-02-09 14:37:23",
}
How can I achieve this with LoDash or vanilla JavaScript? As you can see, there are other common properties like updatedAt and createdAd.
I tried this but I get an empty object
if(this.collection) {
this._auth.getUser(this.collection.uid).subscribe((user) => {
this.user = user;
const col = unionBy(this.user, this.collection, this.collection.uid)
console.log(col)
});
Object.assign() would work for this. Here you can find detail explanation.
See fiddle here
var col = {
"id":"d67de5QJ",
"admins":[
"494949393"
],
"color":"#029ae4",
"components":{
"forums":false,
"pages":true,
"photos":false,
"videos":false
},
"createdAt":"2018-02-09 14:38:59",
"description":"Angular is a TypeS",
"homepage":"pages",
"photoURL":"https://firebase..",
"status":"Public",
"title":"Angular 5",
"uid":"hlyAbEUfJhbxy",
"updatedAt":"2018-02-09 14:38:59"
}
var user = {
"bio": "<strong>PROFILE NEEDS EDITING",
"createdAt": "2018-02-09 12:43:47",
"email": "email#gmail.com",
"avatar": "https://lh5.googleusercontent.com/-3LjYEmTIZlo/A...",
"roles": {
"admin": false,
"dealer": false,
"user": true
},
"status": "online",
"uid": "hlyAbEUfJhbxy",
"updatedAt": "2018-02-09 14:37:23",
}
console.log(Object.assign(col,user))
You can use loadash merge : _.merge. unlike Object.assign, _.merge even handles nested objects. Find the documentation and example here.

tried to access value in object using the incorrect way

Edit
I tried to access value in object using the incorrect way, I have edited this question to stop others from making the same mistake.
Simply store that object into a variable (something like var obj = {...} and type obj.skills to get the skills array back. If you wanted to get test from the cal_strs array, you can do obj.cal_strs[0].test
<pre>
var obj =
{
"skills": [],
"languages": [],
"cal_strs": [{
"test": null,
"primary_test": null
}],
"id": 123,
"my_id": 1346,
"username": "blahblah",
"full_name": "mr blah",
"email": "blah#blah.com",
"location": "boston",
"manager": "boss",
"status": 1,
"abc_status": "here",
"s_s": "2010-06-08T23:00:00Z",
"s_e": "2010-06-13T07:00:00Z",
"n_c": "2010-07-08T07:00:00Z",
"last_here": null
}
console.log(obj.location);
console.log(obj.status);
<pre>
what you have here is a object literal, witch can be manipulated without the use of jquery, to read this object you use the dot notation to get the object value based on the key
obj.key = value
var obj =
{
"skills": [],
"languages": [],
"cal_strs": [{
"test": null,
"primary_test": null
}],
"id": 123,
"my_id": 1346,
"username": "blahblah",
"full_name": "mr blah",
"email": "blah#blah.com",
"location": "boston",
"manager": "boss",
"status": 1,
"abc_status": "here",
"s_s": "2010-06-08T23:00:00Z",
"s_e": "2010-06-13T07:00:00Z",
"n_c": "2010-07-08T07:00:00Z",
"last_here": null
}
console.log(obj.location);
console.log(obj.status);
var abc_status = obj.abc_status;//save the value to a variable
You're trying to access your json object as if it's an array. It's not. You can access your objects already since it's already a proper javascript object (it's not json). Simply store that object into a variable (something like var obj = {...} and type obj.skills to get the skills array back. If you wanted to get test from the cal_strs array, you can do obj.cal_strs[0].test.
Use underscore(_.pluck) get the specific values from the object.
Or try to define a new variable and reassign it .
var s = {
"skills": [],
"languages": [],
"cal_strs": [{
"test": null,
"primary_test": null
}],
"id": 123,
"my_id": 1346,
"username": "blahblah",
"full_name": "mr blah",
"email": "blah#blah.com",
"location": "boston",
"manager": "boss",
"status": 1,
"abc_status": "here",
"s_s": "2010-06-08T23:00:00Z",
"s_e": "2010-06-13T07:00:00Z",
"n_c": "2010-07-08T07:00:00Z",
"last_here": null,
}
var t = {};
t['location'] = s.location;
t['status'] = s.status;
t['abc_status'] = s.abc_status;
t['s_s'] = s.s_s;
t['s_e'] = s.s_e;
t['n_c'] = s.n_c;
in case multiple arrays use underscore.

Indexing array values in an object in an IndexedDB

For a Chrome app, wich stores data in IndexedDB, i have a object like this:
var simplifiedOrderObject = {
"ordernumber": "123-12345-234",
"name": "Mr. Sample",
"address": "Foostreet 12, 12345 Bar York",
"orderitems": [
{
"item": "brush",
"price": "2.00"
},
{
"item": "phone",
"price": "30.90"
}
],
"parcels": [
{
"service": "DHL",
"track": "12345"
},
{
"service": "UPS",
"track": "3254231514"
}
]
}
If i store the hole object in an objectStore, can i use an index for "track", which can be contained multiple times in each order object?
Or is it needed or possibly better/faster to split each object into multiple objectStores like know from relational DBs:
order
orderitem
parcel
The solution should also work in a fast way with 100.000 or more objects stored.
Answering my own question: I have made some tests now. It looks like it is not possible to do this with that object in only 1 objectStore.
An other example object which would work:
var myObject = {
"ordernumber": "123-12345-234",
"name": "Mr. Sample",
"shipping": {"method": "letter",
"company": "Deutsche Post AG" }
}
Creating an index will be done by:
objectStore.createIndex(objectIndexName, objectKeypath, optionalObjectParameters);
With setting objectKeypath it is possible to address a value in the main object like "name":
objectStore.createIndex("name", "name", {unique: false});
It would also be possible to address a value form a subobject of an object like "shipping.method":
objectStore.createIndex("shipping", "shipping.method", {unique: false});
BUT it is not possible to address values like the ones of "track", which are contained in objects, stored in an array. Even something like "parcels[0].track" to get the first value as index does not work.
Anyhow, it would be possible to index all simple elements of an array (but not objects).
So the following more simple structure would allow to create an index entry for each parcelnumber in the array "trackingNumbers":
var simplifiedOrderObject = {
"ordernumber": "123-12345-234",
"name": "Mr. Sample",
"address": "Foostreet 12, 12345 Bar York",
"orderitems": [
{
"item": "brush",
"price": "2.00"
},
{
"item": "phone",
"price": "30.90"
}
],
"trackingNumbers": ["12345", "3254231514"]
}
when creating the index with multiEntry set to true:
objectStore.createIndex("tracking", "trackingNumbers", {unique: false, multiEntry: true});
Anyhow, the missing of the possibility to index object values in arrays, makes using indexedDB really unneeded complicated. It's a failure in design. This forces the developer to do things like in relational DBs, while lacking all the possibilities of SQL. Really bad :(

Trouble parsing json with node.js

I wrote a quick script to parse two fairly large json file (~17k records) to do a comparison of the two. I have confirmed they are both valid json (via jsonlintpro) and the same format. (The source is the same so this should be a given. But, I always assume the mistake is mine. And I still do. Just somewhere else.) However, the parsed file just outputs [object, Object]. I'm wondering what the cause could possibly be?
The json format is like this small snippet (anonymized of course):
[
{
"id": "1234",
"name": "Name1",
"url": "https://localhost/Name1",
"date_created": "2013-07-05T18:47:05Z",
"date_cancelled": "",
"props": [
{
"id": "54321",
"type": "Client",
"value": "General Store"
},
{
"id": "65432",
"type": "Contact_Name",
"value": "Joe Smith"
}
]
},
{
"id": "23456",
"name": "Name2",
"url": "https://localhost/Name2",
"date_created": "2014-02-27T17:46:43Z",
"date_cancelled": "",
"props": [
{
"id": "34567",
"type": "Client",
"value": "Bait Shop"
}
]
}]
And here is the pertinent code:
var _ = require('underscore');
var recs = require('./prod.json');
printArr(recs);
console.log(recs.length);
function printArr(arr) {
arr.forEach(function(item) {
console.log(item + ", ");
});
}
Any guidance would be greatly appreciated.
UPDATE:
Ok, so apparently the issue is with my printArr function. I'm not sure what I'm doing wrong there. I'd like to figure it out because I want to expand upon that so I can print selectively.
the parsed file just outputs [object, Object].
This is the expected behavior BECAUSE you are concatenating an object with a string.
Try console.log(item) instead
console.log(item); should indeed print [object, Object], did you try to output its properties instead?
function printArr(arr) {
arr.forEach(function(item) {
console.log( item.id, item.name, item.url, item.date_created, item.date_cancelled, item.props, ';');
});
}
Just export the value from the prod.json file.
prod.json file
module.exports = [
{
"id": "1234",
"name": "Name1"
},
{
"id": "1234",
"name": "Name1"
}]
elsewhere
var recs = require('./prod.json')
console.log(recs)

Categories

Resources