Ok, so I have a JSON file with lots of information that can be sorted many ways. The actual JSON is too large, but for a relevant example:
$myData =
{
"id":1,
"author_id":[17],
"date":"10/1/1996",
"title":"Article1"
},
{
"id":2,
"author_id":[16,17],
"date":"9/1/1996",
"title":"Article2"
},
{
"id":3,
"author_id":[16],
"date":"6/1/1996",
"title":"Article3"
};
I want to be able to sort this into a struct with the basic structure like:
$myDataByAuthor =
{"17" =
{
"id":1,
"date":"10/1/1996",
"title":"Article1"
},
{
"id":2,
"date":"9/1/1996",
"title":"Article2"
}
},
{"16" =
{
"id":3,
"date":"6/1/1996",
"title":"Article3"
};
{
"id":2,
"date":"9/1/1996",
"title":"Article2"
}
};
I know the syntax there is bad, but I'm not really sure how to lay this out which is why I'm asking.
The reason I want to do this is because I want to turn around and, using ng-repeat in my code be able to output something to effect of:
Author with id 16
6/1/1996 - Article3
9/1/1996 - Article2
Author with id 17
9/1/1996 - Article2
10/1/1996 - Article1
I'm just not seeing how to get this done.
Thanks!
You can certainly restructure it that way, and here is a fiddle and code of the function that would restructure it that way for you.
var table = {}
myData.forEach(function(element){
element.author_id.forEach(function(id){
table[id] = table[id] || []
table[id].push(element)
})
})
https://jsfiddle.net/q40yhhko/
Considering your data is:
$myData = [{ "id":1, "author_id":[17], "date":"10/1/1996", "title":"Article1"},
{"id":2, "author_id":[16,17], "date":"9/1/1996", "title":"Article2"},
{"id":3, "author_id":[16], "date":"6/1/1996", "title":"Article3" }];
To form the required JSON use below code
$scope.requiredJSON = {}; //FORMATED JSON DATA
angular.foreach($myData, function(value, index){
angular.foreach(value.author_id, function(innerVal, innerIndex){
$scope.requiredJSON[innerVal] = $scope.requiredJSON[innerVal] || [];
$scope.requiredJSON[innerVal].push({id: value.id, date: value.date, title: value.title});
})
});
Following is the output:
{17: [{"id":1, "date":"10/1/1996", "title":"Article1" },
{"id":2, "date":"9/1/1996", "title":"Article2" }],
16: [{"id":2, "date":"9/1/1996", "title":"Article2" }]};
https://jsfiddle.net/AmitParrikar/uzv2p72b/2/
Related
I'm trying to group data from an object to a multidimensional array
In the last three days I've tried multiple ways to get the result I want. Since I've no luck, probably because of my poor knowledge of ReactJS/ES6. I hope someone can explain how I can get this to work.
I think I'll have to use the map function. Within the map function, a filter function to get the unique companies and then a loop to add the table information.
The end result should be like this: https://wireframe.cc/No5uB7
The data I'd like to filter:
{
"viewings": [
{
"companyXXX": "company-XXX",
"time_start": "02/04/2019",
"time_end": "03/04/2019 11:59"
},
{
"companyXXX": "company-XXX",
"time_start": "14/04/2019",
"time_end": "15/04/2019 11:59"
},
{
"companyYYY": "company-YYY",
"rejection": 40,
"time_start": "14/04/2019",
"time_end": "15/04/2019 11:59"
}
]
}
The code I still have that isn't working
genData(data) {
const di = data.viewings;
let mps = [];
di.map(m => mps.push(m.company));
mps = Array.from(new Set(mps));
console.log( mps );
let mps = [];
di.map((m) =>
console.log( di.filter(mps => m.company) )
);
}
I might help if your input data was a bit more consistent, especially since you're trying to write m.company, which won't mean anything unless there is a company object in each viewing.
{
"viewings": [
{
"company": "company-XXX",
"time_start": "02/04/2019",
"time_end": "03/04/2019 11:59"
},
{
"company": "company-XXX",
"time_start": "14/04/2019",
"time_end": "15/04/2019 11:59"
},
{
"company": "company-YYY",
"time_start": "14/04/2019",
"time_end": "15/04/2019 11:59"
}
]
}
Then you can write:
var viewings = data.viewings.
var firstViewing = viewings[0];
var firstCompany = firstViewing.company;
var firstTimeStart = firstViewing.time_start;
// etc...
Your input data should be more structured to begin with.
Then you can log out each company name:
var viewings = data.viewings;
viewings.forEach(v => {
console.log(v.company);
});
You mention JSX in your question, but there's no JSX code. This appears to be an issue with your knowledge of JS rather than JSX.
it's me again, now with reactjs.
I have a json, inside it have two "rows", they are Description and ubication. I need to filter the array by Description.
How can I filter this? The description it's in text format for example "Impact" or "Wiu wiu".
I know the function filter() of typescript have a numeric condition but no have a text condition or I haven't seen it been use for that.
Thank you so much for your help.
No still you can do with Text as well,
let filtered = yourArray.filter(t=>t.Description ==='impact');
DEMO
let mydata = {
"ArrayBotones": [
{
"descripcion": "Impacto",
"ubicacion": "sonidos/impacto.mp3"
},
{
"descripcion": "Soy Fede",
"ubicacion": "sonidos/holasoyfede.wav"
},
{
"descripcion": "Wiu wiu",
"ubicacion": "sonidos/wiuwiu.wav"
},
{
"descripcion": "3 carajos",
"ubicacion": "sonidos/3carajos.wav"
},
{
"descripcion": "Apurate Jose",
"ubicacion": "sonidos/apuratejose.wav"
},
{
"descripcion": "No, no se",
"ubicacion": "sonidos/nonose.wav"
}
]
};
let result = mydata.ArrayBotones.filter(t=>t.descripcion === 'Impacto');
console.log(result);
Ok i am trying to implement a query, which is trying to perform regex search ( which contains an array list ) on a bunch of document
Its hard for me to explain...so I am basically coming to direct point.
There is query which works with regex array...
db.paper.find({"category": {$in: [ /xd/, /sd/, /ad/ ] }})
There is query which doesn't works with regex array...
db.paper.find({"category": {$in: [ "/xd/", "/sd/", "/ad/" ] }})
So basically what I want is remove "" sign from string array...so that i can perform below query..
var sea = [ "/xd/", "/sd/", "/ad/" ];
db.paper.find({"category": {$in: sea }});
Using $in can be fairly efficient with small arrays but not so well with huge lists since it will skip around in the index to find the matching documents, or walk through the whole collection if there isn't an index to use.
Besides using the $in with the regular expression, you could use a pipe-delimited regex pattern with the keywords list like this:
Test documents:
db.papertest.insert([
{ category: "ad bd cd" },
{ category: "dd ed fd" },
{ category: "gd hd id" },
{ category: "jd kd ld" },
{ category: "md nd od" },
{ category: "pd qd rd" },
{ category: "sd td ud" },
{ category: "vd wd xd yd zd" },
]);
The magic:
var keywords = ["xd", "sd", "ad"],
regex = keywords.join("|");
db.papertest.find({
"category": {
"$regex": regex,
"$options": "i"
}
});
The results
{ "_id" : ObjectId("56bb6f171bb4f693057c0ba4"), "category" : "ad bd cd" }
{ "_id" : ObjectId("56bb6f171bb4f693057c0baa"), "category" : "sd td ud" }
{ "_id" : ObjectId("56bb6f171bb4f693057c0bab"), "category" : "vd wd xd yd zd" }
it does not work when the double quotes are present because they are interpreted as strings instead of as RegExp objects. So to make it to work, you have to convert it to RegExp objects first in Javascript like this.
var sea = [ "xd", "sd", "ad" ]; // Note: no slashes
var regex = [];
for (var i = 0; i < sea.length; i++) {
regex[i] = new RegExp(sea[i]);
}
db.paper.find({"category": {$in: regex}});
Remember, MongoDB shell uses Javascript
It seems to be working fine for me please try this
var sea = [ "xd", "sd", "ad" ];
var regex = sea.map( function( val ){
return new RegExp( '^['+val+'].*','i' );
})
db.paper.find({"category": { $in: regex }});
For this you can add a regular expression to each item in the array, you can do it in the following way.
data = ['hoLA','Que','TAL', 'Nueva'];
data = data.map(function(v, i){return new RegExp(v, 'i')});
MyCollection.find({"thing": {$in : data}}, function(err, data){
if (err) {
console.log(err)
}else{
data.forEach(function(item){
console.log(item.nombre);
})
}
});
Slightly improved ES6 + TypeScript answer based on Meme Composer comment:
const sea: string[] = [ "xd", "sd", "ad" ];
const regex: RegExp[] = sea.map((value) => new RegExp(value));
db.paper.find({ "category": { $in: regex } });
Here is simple way to transform /.*/ style regex.
var sea = [ "/xd/", "/sd/", "/ad/" ];
var rx = [];
sea.forEach(function name(value) {
var v = value.replace(/\//ig,"");
rx.push(new RegExp(v));
});
db.paper.find({"category": {$in: rx}});
This is a looping question in angularjs. I am little confused about how to get this work. I have a json data:
var jungleData= [
{
"Area": "Safari Lion County",
"htdVideo": "",
"animals": ["lion", "tiger", "Elephant"],
"animalcolor": ["orange", "yellow", "grey"]
},
{
"Area": "Sea World",
"htdVideo": "",
"animals": ["Whale", "Dolphin", "Tarp"],
"animalcolor": ["blue", "grey", "black"]
}
];
I would like to loop thru' the data in angularjs controller (not using ng-repeat in html) and flush out something like this:
Safari Lion County
Lion-black
tiger-yellow
Elephant-grey
Sea World
Whale-blue
Dolphin-grey
Tarp-black
How can I implement this loop? may be a simple question for you guys
This is basically a pure javascript question. Something like:
var jungleDataFlush = function(data)
{
data.forEach(function(place)
{
console.log(place.Area);
console.log();
place.animals.forEach(function(animal,index)
{
console.log(animal + ' - ' + place.animalcolor[index]);
});
console.log();
});
};
jungleDataFlush(jungleData);
Of course you would really want to clean up your model. Animal should be an object, not array:
var animal = { type: 'Lion', color: 'Green' };
I'm trying to merge two objects into a single multidimensional object for use in Angularjs controller by the 'unique_id'. (Note I also have Underscore Js added in).
Object #1 example:
[
{ "unique_id": "001", "title": "Putting Green Challenge - Motion Depends on Force and Mass" },
{ "unique_id": "002", "title": "Molecules to Organisms: Frog Life Cycle" }
]
Object #2 example (has MANY more rows than object 1..):
[
{
"ab_id": "76153F02-29F3-11D8-95EA-951BF95D9AEF",
"unique_id": "001",
"title": "How Speed Relates to Energy",
"state": "NY",
"document_title": "Core Curriculum",
"grade_code": "K-4",
"grade_descr": "Elementary",
"state_id": "1.S2.3a",
"state_text": "Use appropriate \"inquiry and process skills\" to collect data"
},
{
"ab_id": "7980A762-29F3-11D8-BD14-861D7EA8D134",
"unique_id": "001",
"title": "How Speed Relates to Energy",
"state": "NY",
"document_title": "Core Curriculum",
"grade_code": "5-8",
"grade_descr": "Intermediate",
"state_id": "1.S3.2d",
"state_text": "formulate and defend explanations and conclusions as they relate to scientific phenomena"
}
]
My Controller:
abApp.controller("abEE", function(abService, $http, $scope, $q, _) {
var abApp = this;
$scope.abData = $http.get('/data/ab_activities.json', {
cache: false
});
$scope.eeData = $http.get('/activities/eedata', {
cache: false
});
$q.all([$scope.eeData, $scope.abData]).then(function(values) {
var val = ??? This is where I want to merge the objects into one big multidimensional object..
});
Here is the output of console.dir(values);
0 Object { data=[28], status=200, config={...}, more...}
1 Object { data=[743], status=200, config={...}, more...}
This is the desired output I'd like to try and get:
[
{ "unique_id": "001", "title": "Putting Green Challenge - Motion Depends on Force and Mass", "alignments": [{"ab_id": "76153F02-29F3-11D8-95EA-951BF95D9AEF","unique_id": "001","title": "How Speed Relates to Energy",...}, {"ab_id": "7980A762-29F3-11D8-BD14-861D7EA8D134", "unique_id": "001", "title": "How Speed Relates to Energy",...}]
]
Edit
after you updated the question, i created this plunker
hopes it's what you meant
To merge all objects by unique_id
var unions = {};
$q.all([$scope.eeData, $scope.abData]).then(function(values)
{
for (var i = 0; i< values.length; i++)
{
var value = values[i];
if (!unions[value.unique_id])
{
unions[value.unique_id] = {};
}
angular.extend(unions[value.unique_id], value);
}
});
// Do somthing with 'unions'
...
If you could switch to use lodash instead of underscore, it can be achieved like this:
var val = _.values(_.merge(_.indexBy(values[0].data, 'unique_id'), _.indexBy(values[1].data, 'unique_id')));
The underscore doesn't have _.merge(), you have to loop through each property without it.
I don't think angular or underscore have this kind of functionality. I would do something like the following pseudo-code:
tempObject = {}
for object in objectArray
if tempObject[object.unique_id] isnt undefined
tempObject[object.unique_id] = object
else angular.extend(tempObject[object.unique_id], object) // or the other way around depending on your preference
resultingArray = []
for object, key of tempObject
resultingArray.push(object)
You will have to run the for object in objectArray for both the returned arrays but that should work and is probably more efficient than most merge algorithms as at most it will loop through each returned arrays twice.