I am pretty new to JavaScript and Mysql. MySQL query (which I have run in my server-side code in JS) returns rows in this form
i.e. console.log(rows) gives:-
[ RowDataPacket {
id: 7080,
post_author: 134,
post_title: '99 Varieties Dosa, Indira Nagar',
post_content: 'There',
link: '99-varieties-dosa-indira-nagar',
seo_keywords: null,
seo_desc: null,
seo_title: null,
best_for: 'Dosas',
special_info: '',
also_serves: 'Dosas',
'close-timing': '',
address: '56, 9th A Main Road',
direction_landmarks: 'Located in Indira Nagar',
seating: 'Unavailable',
longitude: '77.64097630979995',
latitude: '12.9777060556',
phone_no: ' ',
image_url: null,
location: 'Indira Nagar',
cuisine: 'South Indian Tiffin',
categories: 'Local Food',
Tags: 'Mysore Masala Dosa' }]
[ RowDataPacket {...}]
[ RowDataPacket {...}]
[ RowDataPacket {...}]
[ RowDataPacket {...}]
How can I access the location key of RowDataPacket Object?
I tried rows[i].location, rows[i]["location"], rows.location, rows[i].RowDataPacket.location etc.
When you are doing console.log(rows); you are getting data in the form of JSON array, which can be accessible using below code snippet:
$.each(rows, function(index, data){
// check your index & data details like below & perform other tasks
console.log('INDEX=', index);
consoel.log('DATA=', data); // Here data will be an object
// to access individual key data like location, you can try below code
console.log('LOCATION=', data.location);
});
For further reference you can go through link: https://api.jquery.com/each/
Related
At the bottom is a slimmed down version of a JSON file that I am trying to parse. I would like to create individual objects that have a key for the team name and the player name.
How would I go about using the team name and mapping to each individual player and receive something like this (using javascript):
[
{ name: 'Dallas Stars', playerName: 'Alexander Radulov'},
{ name: 'Dallas Stars', playerName: 'Ben Bishop'},
{ name: 'Dallas Stars', playerName: 'Jamie Benn'}
...
{ name: 'Columbus Blue Jackets', playerName: 'Pierre-Luc Dubois'}
]
From this JSON:
[ { name: 'Dallas Stars',
roster:
[ 'Alexander Radulov',
'Ben Bishop',
'Jamie Benn',
'Tyler Pitlick',
'Miro Heiskanen' ] },
{ name: 'Los Angeles Kings',
roster:
[ 'Jonathan Quick',
'Jonny Brodzinski',
'Oscar Fantenberg' ] },
{ name: 'San Jose Sharks',
roster:
[ 'Joe Thornton',
'Brent Burns',
'Joe Pavelski',
'Antti Suomela' ] },
{ name: 'Columbus Blue Jackets',
roster:
[ 'Sonny Milano',
'Brandon Dubinsky',
'Nick Foligno',
'Pierre-Luc Dubois' ] } ]
Essentially I am trying to map a top level key pair to individual players. I have tried searching through all lodash functions as well and haven't stumbled upon the correct way to do this.
Is there a way to use a flat map and have the team name used multiple times?
You need to iterate over the outer array items, and then inside of each of those, iterate over the roster too. reduce is usually the most appropriate method for transforming an array into another array on a non-one-to-one basis:
const input=[{name:'Dallas Stars',roster:['Alexander Radulov','Ben Bishop','Jamie Benn','Tyler Pitlick','Miro Heiskanen']},{name:'Los Angeles Kings',roster:['Jonathan Quick','Jonny Brodzinski','Oscar Fantenberg']},{name:'San Jose Sharks',roster:['Joe Thornton','Brent Burns','Joe Pavelski','Antti Suomela']},{name:'Columbus Blue Jackets',roster:['Sonny Milano','Brandon Dubinsky','Nick Foligno','Pierre-Luc Dubois']}];
const output = input.reduce((a, { name, roster }) => {
roster.forEach((playerName) => {
a.push({ name, playerName });
});
return a;
}, []);
console.log(output);
You can also use map and flat.
Map over the original array, then for each item being "mapped" map over its roster and create your desired object. Finally, since the resulting array will be 2d, flatten it:
var data = [{ name: 'Dallas Stars', roster: ['Alexander Radulov', 'Ben Bishop', 'Jamie Benn', 'Tyler Pitlick', 'Miro Heiskanen' ] }, { name: 'Los Angeles Kings', roster: ['Jonathan Quick', 'Jonny Brodzinski', 'Oscar Fantenberg' ] }, { name: 'San Jose Sharks', roster: ['Joe Thornton', 'Brent Burns', 'Joe Pavelski', 'Antti Suomela' ] }, { name: 'Columbus Blue Jackets', roster: ['Sonny Milano', 'Brandon Dubinsky', 'Nick Foligno', 'Pierre-Luc Dubois' ] } ];
var res = data
.map(({name, roster}) =>
roster.map(playerName => ({name, playerName})))
.flat();
console.log(res);
In my Angular app with a MongoDB/Node backend, I have been successfully iterating over an array of records and printing them to the view in a table layout - one line per object in the array.
Now I have a situation where I need to break out what was information on one line into three lines, based on info in a "subdata" object. A simplified version of the data looks like this:
data: [
{
name: {
first: "John,
last: "Smith
},
referred: true,
birthDate: date,
city: "New York",
createDate: date,
subdata: {
a: "value a",
b: "value b",
c: "value c"
},
deleted: false
}
]
Rather than iterating once for each object in the "data" array, which I was doing before like this:
<tr *ngFor="let record of records.data | paginate: { id: 'results', itemsPerPage: 12, currentPage: getPageNumber(), totalItems: records.count }">
... I instead need to now print three lines - one for each of the values in the "subdata" object. But each of those lines needs to include the name, the birthDate, and the city that is part of the parent object.
From an architectural point of view, does it make it more sense to create a new backend endpoint, and populate the data in the format I want to iterate over it by (which would involve some repetition of props and values (name, birthDate, city, etc...), like this:
reOrgedData: [
{
name: {
first: "John,
last: "Smith
},
referred: true,
birthDate: date,
city: "New York",
createDate: date,
a: value
deleted: false
},
{
name: {
first: "John,
last: "Smith
},
referred: true,
birthDate: date,
city: "New York",
createDate: date,
b: value
deleted: false
},
{
name: {
first: "John,
last: "Smith
},
referred: true,
birthDate: date,
city: "New York",
createDate: date,
c: value
deleted: false
}
]
or is there a way I can iterate over this in its original data structure, but still break it out into three lines in the view?
My sense is that creating a custom endpoint with the data organized in the form I need is the way to go, even though that does involve some repetition. This approach makes for less hoops-jumping on the front-end. But I am curious for people's take on what would be the best approach in a scenario like this.
Does papaparse support return an array of object instances that are keyed by the header columns?
For example I have a CSV file like this:
sku, location, quantity
'sku1', 'Chicago', 3
'sku2', 'New York, 4
I'd like the array returned by papaparse to look like this:
[{sku: 'sku1', location: 'Chicago', quantity: 3}, ...]
This should also be possible:
results[0].sku == 'sku1'
results[1].quantity == 4
Try adding header: true to the config parameter.
From the docs:
header: If true, the first row of parsed data will be interpreted as field names. An array of field names will be returned in meta, and each row of data will be an object of values keyed by field name instead of a simple array. Rows with a different number of fields from the header row will produce an error. Warning: Duplicate field names will overwrite values in previous fields having the same name.
For example:
Papa.parse('./data.csv', {
download: true,
header: true, // gives us an array of objects
dynamicTyping: true,
complete: ({ data }) => console.log(data),
});
given your data should yield
[
{
sku: 'sku1',
location: 'Chicago',
quantity: 3,
},
{
sku: 'sku2',
location: 'New York',
quantity: 4,
},
]
It is possible by few line in simple javascript working example:
My csv file data:
sku, location, quantity
'sku1', 'Chicago', 3
'sku2', 'New Yoark, 4
I have a lookup object called Locations:
{
'CA:' 'California',
'NV': 'Nevada',
'FL': 'Florida',
...
}
and an array of addresses:
[
{street:'123 place', state:'FL', ...}
]
Is it possible to reference the output of a lookup in a handlebars template tag?
Something like this is what I've tried
{{#each addresses}}
{{Lookup[this.state]}}
{{/each}}
But I get an error. So i'm probably referencing Lookup wrong.
The lookup helper, in addition to being lower-case (not "Lookup"), takes two arguments separated by spaces. The first argument is the path to the object (or array) you want to do the lookup in and the second argument is the key to use. So in your case you probably want {{lookup ../locations this.state}}. Here it is in a snippet:
var source =
'{{#each addresses}}' +
'<li>{{lookup ../locations this.state}}</li>' +
'{{/each}}';
var template = Handlebars.compile(source);
var data = {
locations: {
'CA': 'California',
'NV': 'Nevada',
'FL': 'Florida',
// ...
},
addresses: [
{ street: '123 Place', state: 'FL' },
{ street: '456 Other', state: 'NV' },
{ street: '789 Last', state: 'CA' },
// ...
]
};
document.getElementById('list').innerHTML = template(data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.4/handlebars.js"></script>
<ul id="list"/>
How to parse below JSON code in JavaScript where iterators are not identical?
var js= {
'7413_7765': {
availableColorIds: [ '100', '200' ],
listPrice: '$69.00',
marketingMessage: '',
prdId: '7413_7765',
prdName: 'DV by Dolce Vita Archer Sandal',
rating: 0,
salePrice: '$59.99',
styleId: '7765'
},
'0417_2898': {
availableColorIds: [ '249', '203' ],
listPrice: '$24.95',
marketingMessage: '',
prdId: '0417_2898',
prdName: 'AEO Embossed Flip-Flop',
rating: 4.5,
salePrice: '$19.99',
styleId: '2898'
},
prod6169041: {
availableColorIds: [ '001', '013', '800' ],
listPrice: '$89.95',
marketingMessage: '',
prdId: 'prod6169041',
prdName: 'Birkenstock Gizeh Sandal',
rating: 5,
salePrice: '$79.99',
styleId: '7730'
}
}
How can I parse this JSON in JavaScript? I want the values of prdName, listprice, salePrice in JavaScript?
var products = js; // more semantic
for (productId in products){
var product = products[productId];
console.log (product.prdName , product.listprice, product.salePrice);
}
js is an Object, the for (key in instance) iteration moves through the first level object's attributes, in this case 7413_7765, 0417_2898 and prod6169041, this keys are stored in the var productId, so products[productId] will return the value of this attributes.
Note that the "" in object keynames are not necesary.
You have already assigned the JSON to an object js.
You're trying to loop through JavaScript object, as Edorka mentioned iterate it.