Get Unique object of JSON - json

I have this kind of array:
var foo = [ { "a" : "1" }, { "b" : "2" }, { "a" : "1" } ];
I'd like to filter it to have:
var bar = [ { "a" : "1" }, { "b" : "2" }];
This is my plunker
At line 7 in plunker when i write return JSON.stringify( x ); it is good but returning string JSON.. But when i write return x; it becomes bad and does not return Unique JSON.

You can do this by simply using uniq, not requiring collection:
var uniqueList =_.uniq(foo, function( x ){
return JSON.stringify(x);
});
Updated plunk here: http://plnkr.co/edit/KYW6UybdiBxuvOVX8naP?p=preview

first you can download underscorejs then you can use the following code
var foo = [{ "a": "1" }, { "b": "2" }, { "a": "1" }];
var result = _.uniq(foo, function (obj) {
return JSON.stringify(obj);
});
refere the following url http://underscorejs.org/

You can use var uniqueList =_.uniq(foo, 'a'); Here is doc: https://lodash.com/docs#uniq
here is plunker: http://plnkr.co/edit/HkirGPrs3dGZMUEnEKiT?p=preview

Related

How to get list of documents in the collection till where the sum of 'cost' field has reached a specific value (mongoDb)?

I have a collection:
[
{
_id:1,
dish:pizza,
cost:52
},
{
_id:2,
dish:burger,
cost:33,
},
{
_id:3,
dish:sandwich,
cost:64,
}
{
_id:4,
dish:noodles,
cost:23
},
]
I have a budget set equal to some value say 60.
Is it possible to sort the dishes by cost in asc order and get first n number of documents where sum of costs is less than or equal to 60?
here: cost of 23(noodles)+33(burger)<=60, so these 2 documents are fetched.
output should be:
[
{
_id:4,
dish:noodles,
cost:23
},
{
_id:2,
dish:burger,
cost:33,
}
]
You can try this map-reduce command :
// Variable for map
var _map = function () {
emit(null,this);
};
// Variable for reduce
var _reduce = function (key, values) {
var sum = 0;
var resultArray=[]
for(value in values){
sum=sum+values[value].cost;
if(sum<=60){
resultArray.push(values[value]);
}
}
var result = {};
result.selected=resultArray;
return result;
}
;
db.runCommand({
mapReduce: "01",
map: _map,
reduce: _reduce,
out: { "inline" : 1},
query: {},
sort: {cost:1},
inputDB: "testing",
});
})
Note sort by cost indicated in command. You can filter your doc before map-reduce with the query object.
It will output
{
"_id" : null,
"value" : {
"selected" : [
{
"_id" : 4,
"dish" : "noodles",
"cost" : 23
},
{
"_id" : 2,
"dish" : "burger",
"cost" : 33
}
]
}
}
Quite easy at this point to access to value.selected to get the results.
Hope it helps.

How to remove objoct from object by finding in type script

This is my object
"filterValue":[
{"label":"--Select a Member--","value":""},
{"label":"ghi.jkl","value":{"Id":"1",}},
{"label":"abc.def","value":{"Id":"2",}},
{"label":"asd.vdf","value":{"Id":"3",}},
]
from this i want to search where value.Id = 2 and i want to remove that obeject line.
how can i do that..?
note:first value will be empty there is no data in value.
i have tried something like this:
filterValue.splice( filterValue.indexOf(2), 1 );
You can't use indexOf in this case because you are checking a complex object but you can use findIndex like this:
filterValue.splice( filterValue.findIndex(a => a.Id == 2), 1 );
You might want to change the code the check if findIndex actually found something by checking if it returns something larger than (or equal to) 0.
You can use filter to get a new filtered array (filteredArr):
var arr = [
{"label":"--Select a Member--","value":""},
{"label":"ghi.jkl","value":{"Id":"1",}},
{"label":"abc.def","value":{"Id":"2",}},
{"label":"asd.vdf","value":{"Id":"3",}}
];
var filteredArr = arr.filter((x) => JSON.stringify(x.value) !== JSON.stringify({"Id":"2"}));
console.log(filteredArr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You have a couple of subtly traps to avoid with your specific example.
The structure of items differs, so you need to be careful that you don't have a problem with the "--Select a Member--" item, which doesn't have a value.Id.
The example below cheaply solves the type issue (the best common type between the array members doesn't contain the property you are interested in).
const items = [
{ "label": "--Select a Member--", "value": "" },
{ "label": "ghi.jkl", "value": { "Id": "1", } },
{ "label": "abc.def", "value": { "Id": "2", } },
{ "label": "asd.vdf", "value": { "Id": "3", } },
];
const filtered = items.filter((i: any) => !i.value || !i.value.Id || i.value.Id !== '2');
console.log(filtered);
Output:
[
{"label":"--Select a Member--","value":""},
{"label":"ghi.jkl","value":{"Id":"1"}},
{"label":"asd.vdf","value":{"Id":"3"}}
]
const obj = {
filterValue: [
{ label: "--Select a Member--", value: "" },
{ label: "ghi.jkl", value: { Id: "1" } },
{ label: "abc.def", value: { Id: "2" } },
{ label: "asd.vdf", value: { Id: "3" } }
]
};
var changedObj = obj.filterValue.filter((data, index) => {
return data.value.Id != "1";
});
console.log(changedObj);

How to get total no of count of a field in a Json Array using TypeScript

I have a Json array.
"user": {
"value": [
{
"customerNo": "1234"
},
{
"customerNo": "abcd"
},
{
"customerNo": "1234"
}
]
}
Here I want to get the count of total number of customer. I am getting it like this:
json.user.value.length;
And the output is 3. But the thing is I have to avoid duplicate customer number.
As here "1234" is there 2 times. So my output should be 2
How to do this using Typescript.
Use lodash:
var uniqueCustomer = _.uniqBy(json.user.value, 'customerNo');
var length = uniqueCustomer.length
Here is link which shows How to use lodash in your app.
You can use Array.reduce to count the unique customers.
const data = {
"user": {
"value": [
{
"customerNo": "1234"
},
{
"customerNo": "abcd"
},
{
"customerNo": "1234"
}
]
}
};
function getCustomerCount(arr) {
let tmp = [];
return arr.reduce((acc, curr) => {
if(!tmp.includes(curr.customerNo)) {
return tmp.push(curr.customerNo);
}
return acc;
}, 0);
}
let customers = data.user.value;
let customerCount = getCustomerCount(customers);
console.log(customerCount);

JSON value search

I'm getting below JSON result from a PHP page using ajax request. I tried a lot to get the desired result. I have done below approach but still unable to get as expected.
{
"search": {
"entry": [
{
"attribute": [
{
"name": "title",
"value": [
"Mr."
]
},
{
"name": "mail",
"value": [
"kiran#gmail.com",
"Kiran#yahoo.com",
"kiran#hotmail.com"
]
}
]
}
]
}
}
I have tried the following search to get the value using Defiant.js
success: function (data) {
var xx=JSON.stringify(data);
// var got = $.each(data.search.entry[0].attribute, function (i, v) {
// return v;
//
// });
alert(xx);
var z=JSON.search( xx, '//*[name="title"]/value[1]' );
alert(z);
},
How would I can get results like title='Mr' or mail='kiran#gmail.com'.
Why you need regex solution if your json has proper structure. I have seen your code and json and it seems that you need first index value for title and mail. see following function which can search both title and mail.
var arrt = ' {"search": {"entry": [ {"attribute": [ {"name": "title","value": [ "Mr."] }, {"name": "mail","value": [ "kiran#gmail.com", "Kiran#yahoo.com", "kiran#hotmail.com"] }] }] }}';
SearchMyWordTT(arrt,"title");
//SearchMyWordTT(arrt,"mail");
function SearchMyWordTT(arr,index){
arr = JSON.parse(arr);
for(var i=0;i< arr["search"]["entry"][0]['attribute'].length;i++){
if(typeof (arr["search"]["entry"][0]['attribute'][i]['name']) !="undefined" && arr["search"]["entry"][0]['attribute'][i]['name'] == index)
retIn = arr["search"]["entry"][0]['attribute'][i]['value'][0];
}
return retIn;
}

knockout js mapping nested observable arrays

Given this json structure:
{
"categoryID" : 1,
"categoryName" : "Stupid Questions",
"questions" : [{
"question" : [{
"questionOptions" : [{
"questionOptionID" : 1,
"optionText" : "It's top secret."
}, {
"questionOptionID" : 2,
"optionText" : "Because I am big and your small. I am right and your wrong."
}, {
"questionOptionID" : 3,
"optionText" : "I will gladly pay you Tuesday for a hamburger today."
},
],
"questionType" : "checkbox",
"questionText" : "Why can't we use more abstract table and column names?",
"summary" : "Question of the year"
}
]
}
]
}
I would like to map both the questions and questionOptions to template and templateOptions:
{
"categoryID" : 1,
"categoryName" : "Stupid Questions",
"templates" : [{
"template" : [{
"templateOptions" : [{
"templateOptionID" : 1,
"optionText" : "It is top secret."
}, {
"QuestionOptionID" : 2,
"OptionText" : "Because we are lazy."
}, {
"QuestionOptionID" : 3,
"OptionText" : "I will gladly pay you Tuesday for a hamburger today."
},
],
"QuestionType" : "checkbox",
"QuestionText" : "Why can't we use more abstract table and column names?",
"Summary" : "Question of the year"
}
]
}
]
}
Here is the start to my knockout mapping object:
var templateMapping = {
'templates': {
templates: function(data) {
return ko.utils.unwrapObservable(data.questions);
}
}
//how do I map observable array of question options to observable array of template options here?
};
The key in this mapping is that the sub objects have a different structure (unlike this question - https://stackoverflow.com/a/7535397/466321). It seems like all of the mapping examples I have found don't cover how this may get done, and I have unsuccessfully tried a couple of theories of my own.
#Jeff Mercado is right. The mapper is not intended for this. To accomplish what you intend, it takes a bit of recursive javascript.
function myTransform(string) {
// case-insensitive replace
return string.replace(/question/i,'template');
}
function transformObject(source) {
var result = {}
for( var key in source ) {
if( !source.hasOwnProperty(key) ) continue;
var value = source[key];
var newKey = myTransform(key);
if( Object.prototype.toString.call(value) == "[object Array]" ) {
result[newKey] = [];
for( var i in value ) {
if( !value.hasOwnProperty(i) ) continue;
result[newKey][i] = transformObject(value[i]);
}
}
else if( Object.prototype.toString.call(value) == "[object Object]" ) {
result[newKey] = transformObject(value);
}
else {
result[newKey] = value;
}
}
return result;
}
var wow = transformObject(json);
See this fiddle