How to Combine Multiple Objects by id [duplicate] - javascript

This question already has answers here:
How to combine an array in javascript
(3 answers)
Closed 4 years ago.
I have a dataset which uses the same _id for two different objects and repeats this in the entire file. How do I go through the list of objects, find the two objects that have a matching _id and merge them into one object?
[
{
"_id": "591323037ca83d48eac1ff31",
"sessionStartTime": "2017-05-09T23:10:40.000Z",
"sessionEndTime": "2017-05-10T07:28:40.000Z",
"timeSessionMinutes": 212,
},
{
"_id": "591323037ca83d48eac1ff31",
"eventSummary": "Working",
"eventActivity": "Work",
"eventStart": "2017-05-09T10:00:00+02:00",
"eventEnd": "2017-05-09T17:00:00+02:00"
},
{
"_id": "5917165b3ffac25462193490",
"sessionStartTime": "2017-05-12T22:06:09.000Z",
"sessionEndTime": "2017-05-13T06:12:09.000Z",
"timeSessionMinutes": 322,
},
{
"_id": "5917165b3ffac25462193490",
"eventSummary": "Traveling back home",
"eventActivity": "Travel",
"eventStart": "2017-05-09T17:00:00+02:00",
"eventEnd": "2017-05-09T17:30:00+02:00"
},
...
]
Sorry if already answered, could not find a solution for this specific use case.

An alternative is using the function reduce to group the objects by _id and the function Object.values to extract the grouped objects.
let arr = [ { "_id": "591323037ca83d48eac1ff31", "sessionStartTime": "2017-05-09T23:10:40.000Z", "sessionEndTime": "2017-05-10T07:28:40.000Z", "timeSessionMinutes": 212, }, { "_id": "591323037ca83d48eac1ff31", "eventSummary": "Working", "eventActivity": "Work", "eventStart": "2017-05-09T10:00:00+02:00", "eventEnd": "2017-05-09T17:00:00+02:00" }, { "_id": "5917165b3ffac25462193490", "sessionStartTime": "2017-05-12T22:06:09.000Z", "sessionEndTime": "2017-05-13T06:12:09.000Z", "timeSessionMinutes": 322, }, { "_id": "5917165b3ffac25462193490", "eventSummary": "Traveling back home", "eventActivity": "Travel", "eventStart": "2017-05-09T17:00:00+02:00", "eventEnd": "2017-05-09T17:30:00+02:00" }],
result = Object.values(arr.reduce((a, c) => {
Object.assign((a[c['_id']] || (a[c['_id']] = Object.create(null))), c);
return a;
}, Object.create(null)));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related

How do I create an unique dataset of json object literal in Javascript?

I want to get an output as an unique set of Categories array with the following output [Men,Woman].
Is there any way to do it in Javascript?
For example this my data
{
"products:"[
{
"id": 1,
"categories": {
"1": "Men",
},
},
{
"id": 2,
"categories": {
"1": "Men",
},
}, {
"id": 3,
"categories": {
"1": "Woman",
},
}
];
}
A simple 1 line answer would be
new Set(input.products.map(p => p.categories["1"]))
This is if you're expecting only key "1" in the categories object.
If it can have multiple categories then you can always do
const uniqueCategories = new Set();
input.products.forEach(p => uniqueCategories.add(...Object.values(p.categories)))
Now you can convert a Set into an array
PS: This is not a ReactJs problem but a pure JS question. You might want to remove the ReactJs tag from this question altogether.

map and find the names of all objects [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 1 year ago.
I wanted to map all the names and power of the objects and if he finds an array inside gadgets he would add +1 (i++), how would that be?
The list is much bigger, but I just show these two
"list": [
{
"name": "SHELLY",
"power": 10,
"gadgets": [
{
"id": 23000255,
"name": "FAST FORWARD"
}
]
},
{
"name": "COLT",
"power": 7,
"gadgets": [
{
"id": 23000273,
"name": "SPEEDLOADER"
},
{
"id": 23000319,
"name": "SILVER BULLET"
}
]
]
}
A simple map should do it:
const data = {list:[{name:"SHELLY",power:10,gadgets:[{id:23000255,name:"FAST FORWARD"}]},{name:"COLT",power:7,gadgets:[{id:23000273,name:"SPEEDLOADER"},{id:23000319,name:"SILVER BULLET"}]}]};
const res = data.list.map(p => ({
name: p.name,
power: p.power + p.gadgets.length
}));
console.log(res);

Find the length of JSON object for identical key values [duplicate]

This question already has answers here:
How to count duplicate value in an array in javascript
(35 answers)
Closed 5 years ago.
I have a JSON file. I want to find the length of the JSON object where one key-value pair is similar. Like,
https://api.myjson.com/bins/h5mgv
[
{
"receive_date": "2013-11-04",
"responses": "2",
"name": "west"
},
{
"receive_date": "2013-11-04",
"responses": "8668",
"name": "west"
},
{
"receive_date": "2013-11-13",
"responses": "121",
"name": "east"
}
]
In the above example, length is 2 where "name": "west" and length is 1 where "name": "east" . I want to iterate through the JSON and find the identical values for the key name using Javascript. Output should look like,
east : 1
west : 2
By using length() I can find the length of whole JSON but what is recommended way to find the length for identical key values.
You can use reduce to get a new object listing the count of each name:
const myArray = [
{
"receive_date": "2013-11-04",
"responses": "2",
"name": "west"
},
{
"receive_date": "2013-11-04",
"responses": "8668",
"name": "west"
},
{
"receive_date": "2013-11-13",
"responses": "121",
"name": "east"
}
]
const myCounts = myArray.reduce((counts, item) => {
if (counts[item.name] === undefined) counts[item.name] = 0;
counts[item.name]++;
return counts;
}, {});
console.log(myCounts);
This produces the result:
{
"west": 2,
"east": 1
}

How do I access the responses/response ID's in this JSON string with javascript? [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 10 years ago.
Hi guys I am using parseJSON to parse this JSON string:
json = [
{
"Answers": [
{
"Responses": [
],
"AnswerID": 1,
"AnswerText": "Green"
},
{
"Responses": [
{
"ResponseID": 1,
"RespondingUser": null,
"ResponseDate": "\/Date(1351694241577)\/"
},
{
"ResponseID": 2,
"RespondingUser": null,
"ResponseDate": "\/Date(1351694245093)\/"
}
],
"AnswerID": 2,
"AnswerText": "Blue"
}
],
"QuestionID": 1,
"QuestionText": "Favourite colour?",
"ClosingDate": "\/Date(1351953058527)\/",
"AskingUser": null
}
]
var result = jQuery.parseJSON(json);
but how do I get the responses/response ID's out of 'result' now? Any help would be greatly appreciated!
[ ] = array
{ } = object
You have an array, lose the wrapping square brackets.
alert(json.Answers[0].AnswerText) = "Green"
You should be able to use the for-in loop:
for (i in result[0].Answers)
{
// do something with result[0].Answers[i].Responses
}
Is this what you're looking for?
for (var a in result[0].Answers) {
result[0].Answers[a].AnswerID // Do something with it.
}

How to sort an array of objects in ascending order of number?

I have an array of objects like the following :
var array = {
"112" : {
"id": "3",
"name": "raj"
},
"334" : {
"id": "2",
"name": "john"
},
"222" : {
"id": "5",
"name": "kelvin"
}
}
Now i want to sort the array in ascending order of id and then restore it in array. I tried using sort() but could not do it. Please help how to do so that when i display the data from the array it comes sorted.
Assuming you meant your code to be an array of objects, ie:
var unsortedArray = [
{ id: 3, name: "raj" },
{ id: 2, name: "john" },
{ id: 5, name: "kelvin" }
];
Then you would be able to sort by id by passing a function to Array.sort() that compares id's:
var sortedArray = unsortedArray.sort(function(a, b) {
return a.id - b.id
});
As others have pointed out, what you have is an object containing objects, not an array.
var array = {
"112" : {
"id": "3",
"name": "raj"
},
"334" : {
"id": "2",
"name": "john"
},
"222" : {
"id": "5",
"name": "kelvin"
}
}
var sortedObject = Array.prototype.sort.apply(array);
result:
{
"112": {
"id": "3",
"name": "raj"
},
"222": {
"id": "5",
"name": "kelvin"
},
"334": {
"id": "2",
"name": "john"
}
}
That isn't an array, it is an object (or would it if it wasn't for the syntax errors (= should be :)). It doesn't have an order.
You could use an array instead (making the current property names a value of a key on the subobjects).
Alternatively, you could use a for loop to build an array of the key names, then sort that and use it as a basis for accessing the object in order.
JavaScript objects are unordered by definition. The language specification doesn't even guarantee that, if you iterate over the properties of an object twice in succession, they'll come out in the same order the second time.
If you need things to be ordered, use an array and the Array.prototype.sort method.
That is an object but you can sort an array ilke this:
Working Demo: http://jsfiddle.net/BF8LV/2/
Hope this help,
code
function sortAscending(data_A, data_B)
{
return (data_A - data_B);
}
var array =[ 9, 10, 21, 46, 19, 11]
array.sort(sortAscending)
alert(array);​
Not many people knows that Array.sort can be used on other kinds of objects, but they must have a length property:
array.length = 334;
Array.prototype.sort.call(array, function(a, b) {return a.id - b.id;});
Unfortunately, this doesn't work well if your "array" is full of "holes" like yours.

Categories

Resources