I am working on a Shopify app and part of the order info that I need to get into Mongo is coming as a property that contains a single string via their API. As an example:
"note": "Child 1 First Name: Ali\nChild 1 Gender: Female\nChild 1 Hair Color: Blonde\nChild 1 Hair Style: Wavy\nChild 1 Skin Tone: Tan\nChild 2 First Name: Morgan \nChild 2 Gender: Female\nChild 2 Hair Color: Brown\nChild 2 Hair Style: Ponytail\nChild 2 Skin Tone: Light\nRelationship 1 to 2: Brother\nRelationship 2 to 1: Brother\n",
I actually need this string to look something like this in Mongo:
mongoExDoc: {
child1FirstName: "Ali",
child1Gender: "Female",
child1HairColor: "Blonde",
child1HairStyle: "Wavy",
child1SkinTone: "Tan",
child2FirstName: "Morgan",
child2Gender: "Female",
child2HairColor: "Brown",
child2HairStyle: "Ponytail",
child2SkinTone: "Light",
relationship1To2: "Brother",
relationship2To1: "Brother"
}
Or something along these lines. The property values themselves will NOT change. As you can see each value is separated by \n and each actual value is preceded by a:. I would really appreciate suggestions!
At a glance:
var data = {"note": "Child 1 First Name: Ali\nChild 1 Gender: Female\nChild 1 Hair Color: Blonde\nChild 1 Hair Style: Wavy\nChild 1 Skin Tone: Tan\nChild 2 First Name: Morgan \nChild 2 Gender: Female\nChild 2 Hair Color: Brown\nChild 2 Hair Style: Ponytail\nChild 2 Skin Tone: Light\nRelationship 1 to 2: Brother\nRelationship 2 to 1: Brother\n"};
var mongoExDoc = data.note.split("\n").reduce(function(obj, str, index) {
var strParts = str.split(":");
obj[strParts[0].replace(/\s+/g, '')] = strParts[1];
return obj;
}, {})
console.log(mongoExDoc);
Related
This question already has answers here:
Sort an array of object by a property (with custom order, not alphabetically)
(7 answers)
Closed last year.
I have an array of products where several products can have the same color, and i want to be able to sort this array by the color value. How i would i achieve an Array sorting for example to display all products first that has the color property of "red"? Or any other color that i will tell the array to sort first by.
const arr = [
{
name: "T-shirt",
color: "red",
price: 20
},
{
name: "Shoes",
color: "yellow",
price: 20
},
{
name: "Pants",
color: "red",
price: 20
},
{
name: "Cap",
color: "yellow",
price: 20
},
{
name: "Skirt",
color: "red",
price: 15
},
]
Like this you will sort your array by color, if you want to get the yellow color in first return 1 and red return 2 to have in position 2 etc:
const getRanking = (ele) => {
if (ele.color == "red") return 2;
if (ele.color == "yellow") return 1;
};
arr.sort((a,b) => getRanking(a) - getRanking(b))
This question already has answers here:
Sorting an array of objects by property values
(35 answers)
Closed 4 years ago.
So I have an array like the one in the code below, and I would want to sort it on height. So that the shortest person will log when I do console.log(array[0]);
I have no idea how to do so
let array = [
{
name: "John",
gender: "male",
height_meters: 1.8
},
{
name: "Cathrine",
gender: "female",
height_meters: 1.7
}
]
We seperate out the sort here, it allows us to have clarity to our code, but also makes it easy to swap out or re-use.
Sort is looking for us to return one of three values in order for it to sort elements. Less than zero 0 and Greater than zero. Most documentation will show this as a rigid -1, 0, 1. But any positive and negative can be substituted for the -1 and +1 which gives us the ability to be so concise when sorting numbers.
let array = [
{
name: "John",
gender: "male",
height_meters: 1.8
},
{
name: "Cathrine",
gender: "female",
height_meters: 1.7
},
{
name: "Cathrine",
gender: "female",
height_meters: 1.3
},
{
name: "Cathrine",
gender: "female",
height_meters: 1.95
},
{
name: "Cathrine",
gender: "female",
height_meters: 2.7
}
]
const sortBy = (itemA, itemB) => itemA.height_meters - itemB.height_meters;
console.log(array.sort(sortBy));
Native way
arr.sort((a, b) => a.height_meters - b.height_meters);
With Lodash library
_.orderBy(arr, ['height_meters'], ['asc']);
Use array.sort():
array.sort((a,b)=>{
return a.height_meters-b.height_meters
})
I hope this will help!
I have two json observables I need to join as they originally come separated from another source so this is just an example as I'm trying to understand rxJS too.
var obs = Rx.Observable.from([
{ id: "1", url: "whatever.jpg"},
{ id: "2", url: "whatever2.jpg"},
{ id: "3", url: "whatever3.jpg"}
])
var list = Rx.Observable.from([
{ first: "Gary", last: "Simon", age: "34"},
{ first: "Jane", last: "Simon", age: "34"},
{ first: "Juan", last: "Simon", age: "34"}
])
// I tried this
var newObs = Rx.Observable.merge(list,obs)
// and this
var newObs = Rx.Observable.forkJoin(list,obs)
The point is I need a new json that looks roughly like this:
[{
"first": "Gary",
"last": "Simon",
"age": "34"
},
{
"id": "1",
"url": "whatever.jpg"
}]
How should I do that with RxJS?
Use zip:
Observable.zip(obs, list).subscribe(([obsItem, listItem]) => console.log(obsItem, listItem));
Notes:
The widely used convention is to add $ as a suffix to the observable names. e.g. obs$, list$
If the length of input observables is not the same. The result will take the length of the shortest one. e.g. obs has 3 items, list has 5 items, then the result observable will only emits 3 items and skip the last 2 items of list.
so there is this NodeJS module called console.table where you can basically add tables inside the console. Here is an example from their website:
// call once somewhere in the beginning of the app
require('console.table');
console.table([
{
name: 'foo',
age: 10
}, {
name: 'bar',
age: 20
}
]);
// prints
name age
---- ---
foo 10
bar 20
This is a mere example, I tried to automate it by putting it in a forloop, the forloop and code that I had hoped would work is this:
var values = [
]
for(var l = 0;l<config.accounts.username.length;l++) {
values.push([
{
username: "Number "+l,
itemtype: "Hello",
amount: 10
}, {
itemtype: "Hello",
amount: 10
}
]);
}
console.table("", values);
Unfortunatly though, it does not work, can someone help me with this?
Thanks!
You're pushing an array of values into your array - remove the [ & ]
for(var l = 0;l<config.accounts.username.length;l++) {
values.push(
{
username: "Number "+l,
itemtype: "Hello",
amount: 10
}, {
itemtype: "Hello",
amount: 10
}
);
}
Ref: Array.prototype.push
And then your original example didnt take 2 parameters it only took one so this
console.table("", values);
should possibly be
console.table(values);
Can someone explain in simple terms how reduce function with its arguments reduceAdd, reduceSum, reduceRemove works in crossfilter?
Remember that map reduce reduces a dataset by keys of a particular dimension. For example lets use a crossfilter instance with records:
[
{ name: "Gates", age: 57, worth: 72000000000, gender: "m" },
{ name: "Buffet", age: 59, worth: 58000000000, gender: "m" },
{ name: "Winfrey", age: 83, worth: 2900000000, gender: "f" },
{ name: "Bloomberg", age: 71, worth: 31000000000, gender: "m" },
{ name: "Walton", age: 64, worth: 33000000000, gender: "f" },
]
and dimensions name, age, worth, and gender. We will reduce the gender dimension using the reduce method.
First we define the reduceAdd, reduceRemove, and reduceInitial callback methods.
reduceInitial returns an object with the form of the reduced object and the initial values. It takes no parameters.
function reduceInitial() {
return {
worth: 0,
count: 0
};
}
reduceAdd defines what happens when a record is being 'filtered into' the reduced object for a particular key. The first parameter is a transient instance of the reduced object. The second object is the current record. The method will return the augmented transient reduced object.
function reduceAdd(p, v) {
p.worth = p.worth + v.worth;
p.count = p.count + 1;
return p;
}
reduceRemove does the opposite of reduceAdd (at least in this example). It takes the same parameters as reduceAdd. It is needed because group reduces are updated as records are filtered and sometimes records need to be removed from a previously computed group reduction.
function reduceRemove(p, v) {
p.worth = p.worth - v.worth;
p.count = p.count - 1;
return p;
}
Invoking the reduce method would look like this:
mycf.dimensions.gender.reduce(reduceAdd, reduceRemove, reduceInitial)
To take a peek at the reduced values, use the all method. To see the top n values use the top(n) method.
mycf.dimensions.gender.reduce(reduceAdd, reduceRemove, reduceInitial).all()
The returned array would (should) look like:
[
{ key: "m", value: { worth: 161000000000, count: 3 } },
{ key: "f", value: { worth: 35000000000, count: 2 } },
]
The goals of reducing a dataset is to derive a new dataset by first grouping records by common keys, then reducing a dimension those groupings into a single value for each key. In this case we grouped by gender and reduced the worth dimension of that grouping by adding the values of records that shared the same key.
The other reduceX methods are convience methods for the reduce method.
For this example reduceSum would be the most appropriate replacement.
mycf.dimensions.gender.reduceSum(function(d) {
return d.worth;
});
Invoking all on the returned grouping would (should) look like:
[
{ key: "m", value: 161000000000 },
{ key: "f", value: 35000000000 },
]
reduceCount will count records
mycf.dimensions.gender.reduceCount();
Invoking all on the returned grouping would (should) look like:
[
{ key: "m", value: 3 },
{ key: "f", value: 2 },
]
Hope this helps :)
Source: https://github.com/square/crossfilter/wiki/API-Reference
http://blog.rusty.io/2012/09/17/crossfilter-tutorial/
var livingThings = crossfilter([
// Fact data.
{ name: “Rusty”, type: “human”, legs: 2 },
{ name: “Alex”, type: “human”, legs: 2 },
{ name: “Lassie”, type: “dog”, legs: 4 },
{ name: “Spot”, type: “dog”, legs: 4 },
{ name: “Polly”, type: “bird”, legs: 2 },
{ name: “Fiona”, type: “plant”, legs: 0 }
]);
For example, how many living things are in my house?
To do this, we’ll call the groupAll convenience function, which selects all
records into a single group, and then the reduceCount function, which
creates a count of the records.
// How many living things are in my house?
var n = livingThings.groupAll().reduceCount().value();
console.log("There are " + n + " living things in my house.") // 6
Now let’s get a count of all the legs in my house. Again, we’ll use the groupAll function to get all records in a single group, but then we call the
reduceSum function. This is going to sum values together. What values?
Well, we want legs, so let’s pass a function that extracts and returns the number of legs from the fact.
// How many total legs are in my house?
var legs = livingThings.groupAll().reduceSum(function(fact) {
return fact.legs;
}).value()
console.log("There are " + legs + " legs in my house.")
reduceCount function creates a count of the records.
reduceSum function is the sum values of these records.