Sorting array into array new based on string - javascript

I'm trying to sort a JSON into multiple arrays based on type, my current json is:
// current json file:
{
"res": [
{
"type" : "stream",
"price" : "3.99",
"id" : "13nee"
},
{
"type" : "stream",
"price" : "2.99",
"id" : "8ejwj"
},
{
"type" : "buy",
"price" : "3.99".
"id" : "9akwk"
},
...
]
}
I'm looking to sort it into multiple arrays by type like below:
var sorted = {
"stream" : [
{
"price" : "2.99",
"id" : "8ejwj"
},
{
"price" : ".99",
"id" : "13nee"
},
... // other objects with type: "stream"
],
"buy" : [
{
"price" : "3.99".
"id" : "9akwk"
},
... // other objects with type: "buy"
]
}
I've tried it, but the only solution I can think of is by cases - run if loop, if case matches type, then push object to array. Is there a more elegant solution?

var items = {};
var i = 0;
for(i; i < res.length; i += 1){
var resItem = res[i];
if(items.hasOwnProperty(resItem.type)){
items[resItem.type].push({price:resItem.price, id:resItem.id});
} else {
items[resItem.type] = [{price:resItem.price, id:resItem.id}];
}
}
The properties on JavaScript objects are hashed, so you can dynamically match and generate new objects like above. If you want to apply a well ordering sort, you'll need to apply it to the arrays of the newly generated items object.

Step 1 :
Convert the JSON to a jquery object :
var x = jQuery.parseJSON( jsonString );
Step 2:
Use underscore library's _.groupBy to group :
_.groupBy(x,'type');
There might be some adjustment you need to do for x being array or object.
Edit :
You don't need step1. Just do :
sorted = _.groupBy(json.res,'type');

You could do something like this with ECMA5. This performs, generically, the sort and reduce that you have indicated in your question, so you can add more fields to your data without having to change the routine. It also leaves your original data intact.
Javascript
var original = {
'res': [{
'type': 'stream',
'price': '3.99',
'id': '13nee'
}, {
'type': 'stream',
'price': '2.99',
'id': '8ejwj'
}, {
'type': 'buy',
'price': '3.99',
'id': '9akwk'
}]
},
sorted = {};
original.res.slice().sort(function (a, b) {
a = +(a.price);
b = +(b.price);
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
return 0;
}).reduce(function (acc, element) {
if (!acc[element.type]) {
acc[element.type] = [];
}
acc[element.type].push(Object.keys(element).filter(function (name) {
return name !== 'type';
}).reduce(function (prev, name) {
prev[name] = element[name];
return prev;
}, {}));
return acc;
}, sorted);
console.log(JSON.stringify(sorted));
Output
{
"stream": [{
"price": "2.99",
"id": "8ejwj"
}, {
"price": "3.99",
"id": "13nee"
}],
"buy": [{
"price": "3.99",
"id": "9akwk"
}]
}
On jsFiddle

Related

Merge two objects into one by key, keep duplicates

So I have been looking for a solution to this for a while but can't seem to figure it out. I am trying to merge together the subscriptionArray and userArray by matching on the companyId, but if a company has multiple users (like companyA), I want the subscription Id to repeat and create a new object with a duplicate subscriptionId for each user (see the resultArray). I have a much larger data set i'm working with, but the end goal would be to have an array of every user as an object associated with a subscriptionId, with multiple repeating subscription id's for multiple users.
I am able to merge the two currently, but it doesn't create duplicate subscriptionId objects, it just replaces the previous object.
I can't use ES6, lodash or JQuery, so please just plain vanilla JS
var subscriptionArray = [
{
"subscriptionId" : 2,
"CompanyId" : 20,
},
{
"subscriptionId" : 3,
"CompanyId" : 30,
},
{
"subscriptionId" : 4,
"CompanyId" : 40,
}
]
var userArray = [
{"FirstName" : "Matt",
"CompanyId" : 20,
"CompanyName" : "CompanyA",
},
{"FirstName" : "Bob",
"CompanyId" : 20,
"CompanyName" : "CompanyA",
},
{"FirstName" : "John",
"CompanyId" : 30,
"CompanyName" : "CompanyB",
},
{"FirstName" : "Tim",
"CompanyId" : 40,
"CompanyName" : "CompanyC",
}
]
var resultArray = [
{
"subscriptionId" : 2,
"FirstName" : "Matt"
"CompanyId" : 20,
"CompanyName" : "CompanyA",
},
{
"subscriptionId" : 2,
"FirstName" : "Bob"
"CompanyId" : 20,
"CompanyName" : "CompanyA",
},
{
"subscriptionId" : 3,
"FirstName" : "John"
"CompanyId" : 30,
"CompanyName" : "CompanyB",
},
{
"subscriptionId" : 4,
"FirstName" : "Tim"
"CompanyId" : 40,
"CompanyName" : "CompanyC",
},
]
You really should share what you have tried and what isn't working. That said this is fairly easy to do with Object.assign()
here is a fiddle that shows this in action https://jsfiddle.net/ysy50edf/1/
Lets check out the code:
userArray.forEach( function(user) {
subscriptionArray.forEach( function(sub) {
if( sub.CompanyId == user.CompanyId ){
var result = Object.assign(user, sub);
results.push( result );
}
});
});
Looping each user and then looping over the subscriptions to find the matching property. Then create a new result object that gets assigned the user and the subscription. This merges the two objects and then push that result into your results.
you could do it by using an intermediate structure {[companyId]: items[]} which would be the userArray indexed by company Id (and the values are arrays because multiple people can be in the same company). And then loop onto the subscriptionArray adn return a new correct value.
var userByCompanyId = userArray.reduce(function (users, item) {
if (!users[item.CompanyId]) {
users[item.CompanyId] = [];
}
users[item.CompanyId].push(item);
return users;
}, {});
var subscriptionResultArray = [].concat.apply([], subscriptionArray
.filter(function (item) {
return userByCompanyId[item.CompanyId] !== undefined;
})
.map(function (item) {
var subId = item.subscriptionId;
return userByCompanyId[item.CompanyId].map(function (sub) {
// deepMerge merge recursively objects, see loadash
return deepMerge({}, sub, {
subscriptionId: subId
});
});
}));
Note that I mutate the items in userArray, you can avoid this by using Object.assignin Es6 env or write your own implemantation.

Refactoring object into a flat array

I have an object like this.
{Brunch: 2, Kimchi: 1}
I need to refactor it into an an array/object
[{
"label" : "Brunch",
"value" : 2
},
{
"label" : "Kimchi",
"value" : 1
}]
You can use Object.keys() and map() to get desired result.
var obj = {
Brunch: 2,
Kimchi: 1
}
var result = Object.keys(obj).map(function(k) {
return {
"label": k,
"value": obj[k]
}
})
console.log(result)
The simplest way:
var result = Object.keys(input).map(key => ({
label: key,
value: input[key],
}));

Remove duplicates and merge JSON objects

I have the following JSON object. I need to remove the duplicates and merge the inner object using plain Javascript. How do I go about doing this?
[{
"id" : 1,
"name" : "abc",
"nodes" :[
{
"nodeId" : 20,
"nodeName" : "test1"
}
]
},
{
"id" : 1,
"name" : "abc",
"nodes" :[
{
"nodeId" : 21,
"nodeName" : "test2"
}
]
}]
Following is the object that I expect as output.
[{
"id" : 1,
"name" : "abc",
"nodes" :[
{
"nodeId" : 20,
"nodeName" : "test1"
},
{
"nodeId" : 21,
"nodeName" : "test2"
},
]
}]
Regards.
Shreerang
First turn the JSON into a Javascript array so that you can easily access it:
var arr = JSON.parse(json);
Then make an array for the result and loop through the items and compare against the items that you put in the result:
var result = [];
for (var i = 0; i < arr.length; i++) {
var found = false;
for (var j = 0; j < result.length; j++) {
if (result[j].id == arr[i].id && result[j].name == arr[i].name) {
found = true;
result[j].nodes = result[j].nodes.concat(arr[i].nodes);
break;
}
}
if (!found) {
result.push(arr[i]);
}
}
Then you can create JSON from the array if that is the end result that you need:
json = JSON.stringify(result);
If your string is called input, then this:
var inter = {};
for (var i in input) {
if (!inter.hasOwnProperty(input[i].name)) {
inter[input[i].name] = input[i].nodes;
inter[input[i].name].name = input[i].name;
inter[input[i].name].id = input[i].id;
}
else
inter[input[i].name] = inter[input[i].name].concat(input[i].nodes)
}
results in:
{"abc":[{"nodeId":20,"nodeName":"test1"},{"nodeId":21,"nodeName":"test2"}]}
You can see how I'm using an intermediate object keyed by whatever the match criterion is. It's an object rather than an array as you asked, but you can iterate it anyway. In fact you're probably better off with this structure than the array you asked for.
BTW, I shoved a couple of text-named properties: "id" and "name" into an array there. They don't show up in JSON.stringify but they're there.

sort json object in javascript

For example with have this code:
var json = {
"user1" : {
"id" : 3
},
"user2" : {
"id" : 6
},
"user3" : {
"id" : 1
}
}
How can I sort this json to be like this -
var json = {
"user3" : {
"id" : 1
},
"user1" : {
"id" : 3
},
"user2" : {
"id" : 6
}
}
I sorted the users with the IDs..
I don't know how to do this in javascript..
First off, that's not JSON. It's a JavaScript object literal. JSON is a string representation of data, that just so happens to very closely resemble JavaScript syntax.
Second, you have an object. They are unsorted. The order of the elements cannot be guaranteed. If you want guaranteed order, you need to use an array. This will require you to change your data structure.
One option might be to make your data look like this:
var json = [{
"name": "user1",
"id": 3
}, {
"name": "user2",
"id": 6
}, {
"name": "user3",
"id": 1
}];
Now you have an array of objects, and we can sort it.
json.sort(function(a, b){
return a.id - b.id;
});
The resulting array will look like:
[{
"name": "user3",
"id" : 1
}, {
"name": "user1",
"id" : 3
}, {
"name": "user2",
"id" : 6
}];
Here is a simple snippet that sorts a javascript representation of a Json.
function isObject(v) {
return '[object Object]' === Object.prototype.toString.call(v);
};
JSON.sort = function(o) {
if (Array.isArray(o)) {
return o.sort().map(JSON.sort);
} else if (isObject(o)) {
return Object
.keys(o)
.sort()
.reduce(function(a, k) {
a[k] = JSON.sort(o[k]);
return a;
}, {});
}
return o;
}
It can be used as follows:
JSON.sort({
c: {
c3: null,
c1: undefined,
c2: [3, 2, 1, 0],
},
a: 0,
b: 'Fun'
});
That will output:
{
a: 0,
b: 'Fun',
c: {
c2: [3, 2, 1, 0],
c3: null
}
}
In some ways, your question seems very legitimate, but I still might label it an XY problem. I'm guessing the end result is that you want to display the sorted values in some way? As Bergi said in the comments, you can never quite rely on Javascript objects ( {i_am: "an_object"} ) to show their properties in any particular order.
For the displaying order, I might suggest you take each key of the object (ie, i_am) and sort them into an ordered array. Then, use that array when retrieving elements of your object to display. Pseudocode:
var keys = [...]
var sortedKeys = [...]
for (var i = 0; i < sortedKeys.length; i++) {
var key = sortedKeys[i];
addObjectToTable(json[key]);
}
if(JSON.stringify(Object.keys(pcOrGroup).sort()) === JSON.stringify(Object.keys(orGroup)).sort())
{
return true;
}

Move an object (element) one step up with Javascript

I have several objects like this:
I want to move type and value one step up so they will be next to field, and then delete data.
It looks like this when departments is converted to JSON:
[
{"field" : "DEPARTMAN_NO",
"data" : { "type":"numeric" , "comparison":"eq" , "value":11 }
},
{"field" : "DEPARTMAN_ADI",
"data" : { "type":"string" , "value":"bir" }
}
]
I have tried:
departments = grid.filters.getFilterData();
i = {};
for(var i in department) {
department = i.data;
delete.department.data;
};
but it dosen't work.
1) First, loop departments, each item we call it department;
2) You want to move department.data's properties to department, From another angle, you can move department's properties to department.data and return department.data, code like:
var departments = [{
"field": "DEPARTMAN_NO",
"data": {
"type": "numeric",
"comparison": "eq",
"value": 11
}
}, {
"field": "DEPARTMAN_ADI",
"data": {
"type": "string",
"value": "bir"
}
}],
department;
for (var i = 0, len = departments.length; i < len; i++) {
department = departments[i]; // department
for (var key in department) {
if (key !== 'data' && department.data) {
department.data[key] = department[key];
}
}
departments[i] = department.data || department; // if no department.data, no change
}
console.log(departments);
result:
view the full demo http://jsfiddle.net/KVYE5/
I wrote a little npm package that does what you're asking for: moving a property up a level in an object.
You can get it here: https://www.npmjs.com/package/move-property-up-a-level
Usage
var movePropertyUpALevel = require('movePropertyUpALevel');
var fakeObj = {
poodle: {
first: {
hey: 'you'
},
second: 'meAgain'
}
};
movePropertyUpALevel(fakeObj, 'poodle');
console.log(fakeObj.first.hey);
//'you'
console.log(fakeObj.poodle);
//undefined
obj =
[
{"field" : "DEPARTMAN_NO",
"data" : { "type":"numeric" , "comparison":"eq" , "value":11 }
},
{"field" : "DEPARTMAN_ADI",
"data" : { "type":"string" , "value":"bir" }
}
];
for ( var item in obj ) {
if ( obj[item].field && obj[item].data ) { //check the 'field' and 'data' exist
obj[item].field = {
dept : obj[item].field , //department name is put into a property
type : obj[item].data.type, //so is data.type and data.value..
value: obj[item].data.value //..all are now contained in 'field'
};
delete obj[item].data; //remove the 'data' object
}
}
console.log(obj);
department.type = department.data.type;
department.value = department.data.value;
delete department['data'];

Categories

Resources