How to convert a array of objects into string in nodejs? - javascript

[
RowDataPacket {
House_Name: 'Merlin 5th Avenue',
no_of_rooms: 6,
Cost: 3400000,
PropertyId: 2
},
RowDataPacket {
House_Name: 'Presidential Building',
no_of_rooms: 5,
Cost: 3500000,
PropertyId: 106
},
RowDataPacket {
House_Name: 'GreenSlide Building',
no_of_rooms: 4,
Cost: 6300000,
PropertyId: 107
},
RowDataPacket {
House_Name: 'RabindraNath Building',
no_of_rooms: 4,
Cost: 5500000,
PropertyId: 108
},
RowDataPacket {
House_Name: 'CityView Apartment',
no_of_rooms: 3,
Cost: 4300000,
PropertyId: 109
}
]
I have this array of objects that I want to convert to string so that I can pass it in the get request to some other page. How can I convert the array of objects to string.
The number of objects in the array is dynamic and can change. The array shown above is just one example.
Is there any other way to pass array in a get request?
I am passing the array into a jade file, which then calls a get request?
doctype html
html(lang='en')
head
meta(charset='UTF-8')
title Property List
link(rel='stylesheet', href='/stylesheets/prop-list-style.css')
link(href='//netdna.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css', rel='stylesheet')
link(rel='stylesheet', href='/stylesheets/likeButton.css')
body
// partial:index.partial.html https://picsum.photos/500/300/?image=10
.main
h1(data-text='Property List') Property List
- var prop = props
ul.cards
for pip in prop
li.cards_item
.card
.card_image
img(src='https://picsum.photos/500/300/?image=10')
.card_content
h2.card_title #{pip.House_Name}
p.card_text #{pip.no_of_rooms} BHK
a(href='/signIn/interested?id=#{pip.PropertyId}&cid=#{customerid}&values=#{properties}')
i.like-button.fa.fa-2x.fa-heart-o(class='#{like}')
p.card_text Price: #{pip.Cost}
a(href='/signIn/readMore?id=#{pip.PropertyId}&cid=#{customerid}&values=#{properties}')
button.btn.card_btn Find Out More
else
h2 No such property exist
script(src='/javascripts/likebutton.js')
// partial
The #{properties} variable is the variable which holds the array and is a part of the get request.

You can try using this code for converting array of objects in to string
first assign the array of objects to a variable and then use json.stringify() method to convert array of objects in to string
var random = [{},{},{}.....];
JSON.stringify(random);
and to convert string back to array of objects use
JSON.parse(random);
And also you are making the array of objects wrongly it should be like this and then the above stringify and parse method will work completely fine.
[
{
House_Name: 'Merlin 5th Avenue',
no_of_rooms: 6,
Cost: 3400000,
PropertyId: 2
},
{
House_Name: 'Presidential Building',
no_of_rooms: 5,
Cost: 3500000,
PropertyId: 106
},
{
House_Name: 'GreenSlide Building',
no_of_rooms: 4,
Cost: 6300000,
PropertyId: 107
},
{
House_Name: 'RabindraNath Building',
no_of_rooms: 4,
Cost: 5500000,
PropertyId: 108
},
{
House_Name: 'CityView Apartment',
no_of_rooms: 3,
Cost: 4300000,
PropertyId: 109
}
]

Related

How to make a Leaderboard using objects inside objects? Javascript

so I am trying to make a leaderboard of the players with more points, the object kinda looks like this:
let currency = {
person1: {
money: 1004,
level: 20
},
person2: {
money: 124,
level: 3
},
person3: {
money: 50144,
level: 102
}
}
and what I want to do is it to create a leaderboard based on everyone's MONEY (not level)
For example:
person3 | 50144
person1 | 1004
person2 | 124
Any help will be appreciated since i have been stuck in this part.
Try iterating over your object using Object.entries, then you can filter the output array with Array.sort() and finally just Array.map() in order to get your desired format.
const currency = {
person1: {
money: 1004,
level: 20,
},
person2: {
money: 124,
level: 3,
},
person3: {
money: 50144,
level: 102,
},
};
const result = Object.entries(currency)
.sort((a, b) => b[1].money - a[1].money)
.map((p) => `${p[0]} | ${p[1].money}`);
console.log(result);

Looking for a way to sort an array of objects in javascript

so I have a JSON array that looks like this:
[
{
row: [
{
boat: {
description: 'Books',
version: '2',
id: 6
},
airplanes: [
{
airplane: [
{
description: 'DVD',
version: 2,
uid: 69,
wid: 65,
id: 84
}
],
trains: {
train: [
{
description: 'Pictures',
version: 2,
id: 149
}
],
actions: [
{
description: 'This is a really long sentence.',
version: 2,
tid: 69.01,
id: 452
},
{
description: 'article 2',
version: 2,
tid: 69.02,
id: 453
},
{
description: 'developer 1',
version: 2,
tid: 69.03,
id: 454
}
]
}
},
{
airplane: [
{
description: 'Games',
version: 2,
uid: 65,
wid: 61,
id: 80
}
],
trains: {
train: [
{
description: 'another great descriptions.',
version: 2,
id: 145
}
],
actions: [
{
description: 'being indecisive is good.',
version: 2,
tid: 65.01,
id: 442
},
{
description: 'couches are comfortable',
version: 2,
tid: 65.02,
id: 443
}
]
}
}
]
}
]
}
]
I am trying to sort the above output by 'wid' in ascending order but still be able to preserve the overall order. For example in the above the wid in element 0 of the array is 65, and element 1 of the array the wid value is 61. Therefore, element 1 and element 0 should be swapped. Is there any built in javascript method to sort json like this?
I will have a json array output a lot larger than the provided example.
Both Underscore and LoDash have a sort method that will do what you're looking for. In this example I am assuming that you have the data structure you showed stored in a variable called data.
_.each(data, function(obj) {
_.each(obj.row, function(row) {
// note the reassignment, _.sortBy does not sort in-place
row.airplanes = _.sortBy(row.airplanes, function(airplane) {
return airplane.wid; // This will sort ascending.
// To sort descending, simply multiply by -1
});
});
});
So what is this doing? It's taking each array element in your root data structure and looping over it (that's the first _.each). Then in each of those objects, it is looping over each row element and sorting row.airplanes array by the wid element contained in each.
Hopefully this helps you. As an aside, that data you posted is strictly invalid JSON. Each key should be double quoted, i.e., "row", instead of just row and single quotes are invalid for delimiting strings, i.e., "DVD" instead of 'DVD'. Also, your boat version is a string whereas your other version identifiers are integers, it's a good idea to try and keep your version identifiers as integers.
I recommend using the excellent jq commandline JSON processor. Extremely fast since it was written in portable C. Easy to understand documentation.
cat <file.json> | jq . -S

JSON object - Accessing Values in React Native

In my React Native application I am using the RNDBModels package that is a wrapper over AsyncStorage. Currently I am saving a JSON object through RNDBModels and that works correctly, however accessing the data is proving challenging.
When the code is return from the get method, it is return inside a JSON Object and I would essentially like the values from the result, so that I can iterate over it for a list.
The returned result:
{
'1':
{
name: 'Galaxy',
description: '20gram bars',
_id: 1
},
'2':
{
name: 'Snickers',
description: 'Hazelnuts',
count: 2,
_id: 2
}
}
And the desired outcome so that I can easily iterate over the objects in the array and then render a list in React Native.
[
{
name: 'Galaxy',
description: '20gram bars',
_id: 1
},
{
name: 'Snickers',
description: 'Hazelnuts',
count: 2,
_id: 2
}
]
Any suggestions at accessing the values? I have tried using Object.keys and then subsequently Object.values to no avail sadly.
You can do it with the in operator :
const data = {
'1': {
name: 'Galaxy',
description: '20gram bars',
_id: 1
},
'2': {
name: 'Snickers',
description: 'Hazelnuts',
count: 2,
_id: 2
}
};
var array = [];
for (let prop in data) {
array.push(data[prop]);
}
console.log(array);
JSFiddle
If you're using lodash just one line of code would work for your purpose
_.values(YOUR_OBJECT);
https://lodash.com/docs#values
It will make an array of values from your object.

How could I aggregate among multiple collections at once with loop

Suppose Each collection has these common fields birthday, gender
How could I get the grouped birthday with year by group
expected result
group r01 {id: 1987, count: 21121}, {id: 1988, count: 22}, ...
The output should count for user_vip_r01 and user_general_r01
group r15 {id: 1986, count: 2121}, {id: 1985, count: 220}, ...
The output should count for user_vip_r15 and user_general_r15
I know how to write the group by year query,
But don't know how to write an loop to iterate all my collection with javascript.
And what if the collection name is part of irregular,
Something like user_old_r01, user_new_r01, user_bad_r01, should all be processed in group r01,
Is it possible to use regex to get it ?
group by year
pipeline = [
{ '$group':
'_id': '$year': '$birthday'
'count': '$sum': 1
}
{ '$sort': '_id': 1 }
]
cur = db[source_collection].runCommand('aggregate',
pipeline: pipeline_work.concat([{ '$out': output_collection_name}])
allowDiskUse: true)
collection list
"user_vip_r01",
"user_vip_r15",
"user_vip_r16",
"user_vip_r17",
"user_vip_r18",
"user_vip_r19",
"user_vip_r20",
"user_vip_r201",
....
"user_general_r01",
"user_general_r15",
"user_general_r16",
"user_general_r17",
"user_general_r18",
"user_general_r19",
"user_general_r20",
"user_general_r201",
...

Javascript Object to a different form

I'm having trouble converting the follow result from elasticsearch into a different form. Is there a quick way to do this, or would jumping in a for loop be necessary? Thanks in advance:
The format my data is in:
This is how it is in raw format:
[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
1. 0: Object
1. count: 986
2. term: "virginia"
3. __proto__: Object
2. 1: Object
1. count: 447
2. term: "washington"
3. __proto__: Object
3. 2: Object
1. count: 345
2. term: "newYork"
The Format I need to convert to:
var states= [
{
"key": 'popular',
"values": [
[ 'texas' , 10] ,
[ 'washington' , 5] ,
[ 'new york' , 20] ,
[ 'virginia' , 40]
]
}
];
To help show what the data looks like, this image shows the format from console:
Looking at your sample data, it appears to be an array of objects, each with a term and count property. Array#map would do the trick for converting it into arrays with the term in the first position and the count in the second:
var states= [
{
"key": 'popular',
"values": data.map(function(entry) {
return [entry.term, entry.count];
})
}
];
Live example:
var data = [
{
term: "virginia",
count: 986
},
{
term: "washington",
count: 447
},
{
term: "newYork",
count: 345
}
];
var states= [
{
"key": 'popular',
"values": data.map(function(entry) {
return [entry.term, entry.count];
})
}
];
// Result (I'm only using JSON here as a convenient way to
// display the result; the question doesn't use JSON at all)
var pre = document.createElement('pre');
pre.innerHTML = JSON.stringify(states, null, 2);
document.body.appendChild(pre);

Categories