Extract part of an object to an array - javascript

I have an array of hundreds of objects like the following:
{
"id" : 893,
....
"responsable" : {
"id" : 792,
"version" : 13,
"username" : "xxxxx#mail.es",
"nombre" : "Peter",
"apellido1" : "Murphy",
"apellido2" : "XXX"
}
}
Within my object I have another object that is "responsable". Need to get an array of these objects, but only once each (remove repeated)

You can use reduce to summarise your data to an object. And use Object.values to convert the object into an array.
This example will extract all responsables and remove duplicates based on responsable.id
let arr = [
{"id": 893,"responsable": {"id": 792,"version": 13,"username": "xxxxx#mail.es","nombre": "John","apellido1": "Murphy","apellido2": "XXX"}},
{"id": 894,"responsable": {"id": 793,"version": 13,"username": "xxxxx#mail.es","nombre": "Peter","apellido1": "Murphy","apellido2": "XXX"}},
{"id": 895,"responsable": {"id": 792,"version": 13,"username": "xxxxx#mail.es","nombre": "John","apellido1": "Murphy","apellido2": "XXX"}},
{"id": 896,"responsable": {"id": 794,"version": 13,"username": "xxxxx#mail.es","nombre": "Paul","apellido1": "Murphy","apellido2": "XXX"}}
];
let responsable = Object.values(arr.reduce((c, v) => Object.assign(c, {[v.responsable.id]: v.responsable}), {}));
console.log(responsable);

Related

How to aggregate objects with dates as keys in javascript

I have an object with keys as dates in the following format "yyyy-mm-dd" (ex: 2020-08-14)
the value of each key is an array of objects with two attributes, name and value.
I need to find a way to get the sum of the keyvalue grouped by name accros N days.
Here is an example to better understand, the original object have 4 days of data, with one day having an empty array:
{
"2020-10-15":[
{"name":"France","value":20},
{"name":"United States","value":20},
{"name":"Italy","value":5},
],
"2020-10-16":[
{"name":"Germany","value":10},
{"name":"United States","value":5},
{"name":"France","value":10}
],
"2020-10-17":[],
"2020-10-18":[
{"name":"UK","value":10},
{"name":"Italy","value":10},
]
}
For example if we wish to group this data by 4 days we will get the following:
[{"name": "France", "value": 30},
{"name": "United States", "value": 25},
{"name": "Italy", "value": 15},
{"name": "Germany", "value": 10},
{"name": "UK", "value": 10}]
This is the sum of all objects with same value for name across 4 days. I have absolutly no idea how to achieve this, I know can use map to iterate the object keys and do some processing through moment js but I don't know how to achieve this.
You can do the following using reduce, forEach and Object.keys method,
const value = {
"2020-10-15":[
{"name":"France","value":20},
{"name":"United States","value":20},
{"name":"Italy","value":5},
],
"2020-10-16":[
{"name":"Germany","value":10},
{"name":"United States","value":5},
{"name":"France","value":10}
],
"2020-10-17":[],
"2020-10-18":[
{"name":"UK","value":10},
{"name":"Italy","value":10},
]
}
let res = Object.keys(value).reduce((prev, curr) => {
value[curr].forEach(item => {
const idx = prev.findIndex(pItem => pItem.name === item.name);
if(idx > -1) {
const newObj = {...prev[idx], value: prev[idx].value + item.value};
prev[idx] = newObj;
return ;
}
prev.push(item);
})
return prev;
}, []);
console.log(res);

Intersperse elements into array but if array is too long, split it up

I have a Set of userId strings like this:
["1", "2", "3"....]
I want to loop over and convert them to this object format:
[
{
"field" : "tag",
"key" : "user_id",
"relation": "=",
"value" : 1 // Insert userId here
},
etc...
]
And then in between the userId objects I need to add the object:
{ "operator": "OR" }
So the array looks like
[{userId object}, {OR object}, {userId object}, etc...]
There are an arbitrary number of userIds - there could be thousands. What I need to happen is, if there are more than 200 objects in the array, I need to call the function sendObjects(array) with that object array, and then reset the array and continue from where I left off. The array must not end in an OR object. How to do this??
Use forEach() on array numArray:
var numArray = ["1", "2", "3"];
var res = [];
numArray.forEach(function(val, index){
var obj = {
"field" : "tag",
"key" : "user_id",
"relation": "=",
"value" : val
};
res.push(obj);
if(numArray.length-1 !== index){
res.push({ "operator": "OR" });
}
});
console.log(res);

Create nested JSON array

I'm trying to create a JSON array to send it to my web service. This is how my json should look like:
[{
"tipus": 1,
"proveidor": 3,
"atributs": {
"atribut":{
"id": 1,
"valor": 8
},
"atribut":{
"id": 2,
"valor": 500
}
}
}]
So, I have two general values "tipus" and "proveidor" and multiple "atributs" each "atribut" is composed with "id" and "valor".
When I construct the json I get this instead of what I want:
[
2:{
"tipus": 1,
"proveidor": 3,
1:{
"id": 1,
"valor": 8
},
0:{
"id": 2,
"valor": 500
}
}]
This is how I'm building the json:
// For every founded in $scope.atrb i need to create an 'atribut' element into my json
$scope.a = [];
var key;
for(key in $scope.atrb){
var newField = {
"idatributs_actiu": $scope.atrb[key].idatributs_actiu,
"nomAtribut": $scope.atrb[key].nomAtribut,
"valor": $scope.atrb[key].valor,
"idActiu": $routeParams.idTipusActiu,
"value": "",
"ordre": $scope.atrb[key].ordre,
"idatributs_generics": $scope.atrb[key].idatributs_generics
};
$scope.a.push(newField);
}
$scope.f = $scope.a;
});
var generics = {
"nom": $scope.nom,
"tipus": $routeParams.idTipusActiu,
"proveidor": $scope.proveidor.id
};
$scope.a.push(generics);
It's my first project with angular and I'm not sure if I'm building the json appropriately, basically i use an array to build a json but I don't know how to nested it 'atribut' inside 'atributs'.
The main idea is to read the 'generics' atributes and then loop through 'atributs' and read all 'atribut' element getting the properties.
Regards
Like S4beR and Kevin B told me, I just need to do an JS array. This is in my controller:
var obj = { generics: g, atributs: $scope.a };
g: it's an object with the generic properties
$scope.a: this is an array with 'atribut' objects which contais all
the properties I need save to.

Jquery JSON decode multiple arrays

I have this multiple set of data as array
data = [{"id": "1", "name" : "abc", "key1" : "value12 }, {"id": "2", "name" : "cde", "key2" : "value2" }.....]
I need to get this data using jQuery
json = $.parseJSON(data);
but how do I access the parsed JSON data? json.id shows the result as undefined.
Thanks
Update : Sorry I fixed the above example JSON I gave, I just quickly typed it by myself and it's not the original json I'm having trouble with. I just gave it to give an idea about the problem that I was having. Thanks for the answers :)
It isn't JSON. It isn't even JavaScript.
If you fix the syntax errors (such as the missing quotes and the missing commas between the array items) then it is an array literal (containing object literals which contain …). Don't parseJSON it (you use that on JSON texts stored in JavaScript strings).
Since it is an array. It doesn't have an id. It has a number of numerical indexes.
var someObject = data[0];
The objects stored on those indexes have ids.
var id = someObject.id;
Your json is invalid. ',' are missing between objects.
Suppose if json is :
data = [{"id": "1", "name" : "abc", "key1" : "value12" }, {"id": "2", "name" : "cde", "key2" : "value2" }]
Then you can access 'id' element using this :
data[0].id
Try this:
var data = '{"id": "1", "name" : "abc", "key1" : "value12" } , {"id": "2", "name" : "cde", "key2" : "value2"}';
var obj = JSON.parse('[' + data + ']');
alert(obj[0].id);
Here is demo
Your json is invalid,
data = [{"id": "1", "name" : "abc", "key1" : "value12" }, {"id": "2", "name" : "cde", "key2" : "value2" }.....]
Retrive using:
var id = data[0].id;
console.log(id);

How to get json object key name from collection and iterate

Below is my json structure. On success of collection.fetch() i'm looping through the structure.
Currently i use
this.collection.each(function(model) { .. }
How do i obtain key name like plants, animals and instead loop using the names.
JSON
var jsonObj = { // 0 - recommended , 1 - New
"plants" : [
{
"title" : "title1",
"desc": "description.."
},
{
"title" : "titl2",
"desc": "description."
}
],
"animals" : [
{
"title" : "title1",
"desc": "description.."
},
{
"title" : "titl2",
"desc": "description."
}
]
};
Snapshot of collection
This would work, but you'd use a normal for loop, not "each":
for(i in jsonObj){
alert(i);
}
here is a fjsfiddle: http://jsfiddle.net/r5nwP/
Is that what you're after?
You can use the underscore keys to get a list of names:
var thenames =_.keys(yourobject);
In this case thenames will contain a list of the keys you are looking for. Here is the documentation for it:
http://underscorejs.org/#keys
keys_.keys(object)
Retrieve all the names of the object's properties.
_.keys({one : 1, two : 2, three : 3});
=> ["one", "two", "three"]

Categories