I'm wondering if something like this is possible - an extend that looks at an array of objects
Lets say I have :
myObj = [
{"name" : "one", "test" : ["1","2"]},
{"name" : "two", "test" : ["1","2"]}
]
And I'm trying to extend into that
{"name" : "one" , "test" : ["1","3"]}
So the result would be -
myObj = [
{"name" : "one", "test" : ["1","2", "3"]},
{"name" : "two", "test" : ["1","2"]}
]
And this would be like extend in that if there is no object there it would just create one. IS something like this possible? Thanks!
It looks like you want something like:
function deepSetMerge(base, next) {
var dataEntry = base.filter(function(it) {
return it.name === next.name;
})[0];
if (dataEntry) {
var diff = next.test.filter(function(it) {
return dataEntry.test.indexOf(it) === -1;
});
dataEntry.test = dataEntry.test.concat(diff).sort();
} else {
base.push(next);
}
}
var data = [{
"name": "one",
"test": ["1", "2"]
}, {
"name": "two",
"test": ["1", "2"]
}];
var add = {
"name": "one",
"test": ["1", "3"]
};
var obj = {
"name": "totally-unique",
"test": [1, 2, "nine", 17.0]
};
deepSetMerge(data, add);
deepSetMerge(data, obj);
document.getElementById('results').textContent = JSON.stringify(data);
<pre id="results"></pre>
This function works by finding the existing entry, by name, if one exists. If not, we just push the object to be merged in as a new entry.
If the entry does exist, find the difference between the two sets of items, then concatenate them onto the end of the existing array (and sort the results).
This is pretty specific to your data structure and not the most flexible solution in the world, but hopefully shows the algorithm well.
As a universal extend implementation this would be quite tricky and costly. It is why deep dives are usually avoided. It is better to know your data model and work with it that way.
Using your example I would establish some assumptions on the data model in question:
Our object will have a name property which is unique and can be searched for.
The value of the test property is an array (makes this easier but it could be an object that you use a typical extend implementation on.
In which case you could approach it like this:
var myObj = [
{name: 'one', test: ['1', '2']},
{name: 'two', test: ['1', '2']}
];
function extendTestValue(data, value) {
var names = data.map(function(item) {
return item.name;
});
var index = names.indexOf(value.name);
if (index < 0) {
data.push(value);
} else {
value.test.forEach(function(item) {
if (data[index].test.indexOf(item) < 0) {
data[index].test.push(item);
}
});
}
return data;
}
Related
I need get data the my Json but I can't use 'key' because the 'key' is different each day.
I tried :
template: function(params) {
const objects = JSON.parse(JSON.stringify(params.data.masterdetail));
for (const obj of objects) {
const keys = Object.keys(obj);
const cont = 0;
keys.forEach(key => {
const valor = obj[key];
console.log('value ', valor[0]);
});
}
I first tried with 0 and then use cont, but with 0 console.log (value is undefined)....
If I use console.log ('value' , valor['name']) IT'S OK ! but I can't use keys and if I use valor[0] is undefined...........
Example Json
{
"headers": [
"headerName": "asdasd",
], //end headers
"datas": [
"idaam": "11",
"idorigen": "11",
"masterdetail": [{
"child1": {
"name": "I AM",
"age": "1"
},
"child2": {
"name": "YOU ARE",
"age": "2"
},
"child3": {
"name": "HE IS",
"age": "3"
},
}] //end masterdetail
]//end datas
}//end JSON
Edit :
I can't use 'keys' because today I receive "name", "typeval" etc. and tomorrow I can get 'surname','id' etc.
If you see in my first img you can see "4" bits of data.
1º obj[key]{
name = "adopt",
typeval= "",
etc
}
2º obj[key]{
"link" = "enlace",
"map" = "map"
etc
}
If I use this code : I get "name" OKEY but
I HAVE PROHIBITED use of value['name'] or value[typeval] because this Json always is dynamic.
var objects = params.data.masterdetail[0];
const keys = Object.keys(objects);
let value;
keys.forEach(key => {
value = objects[key];
console.log(value['name']);
console.log(value['typeval']);
});
I need for example :
var objects = params.data.masterdetail[0];
const keys = Object.keys(objects);
cont = 0 ;
keys.forEach(key => {
value = objects[key];
console.log(value[0]);
});
but value[0] is undefined and then when I arrive 2ºobj[key] link is index 0 but cont maybe is .... 4...
Sorry for my English...
To simply print the objects within the first entry in the masterdetail array, you can do the following:
var objects = params.datas.masterdetail[0];
const keys = Object.keys(objects);
keys.forEach(key => {
console.log('value ', objects[key]);
});
Based on a (suitably corrected - see my comments above) version of the JSON above, this would produce console output as follows:
value {name: "I AM", age: "1"}
value {name: "YOU ARE", age: "2"}
value {name: "HE IS", age: "3"}
Unfortunately it's not 100% clear from the question if this is the output you were looking for, but that's my best guess based on the code.
Your main mistakes were that
1) masterdetail is an array, and all the data is within the first element of that array, so to get the objects within it you need to select that element first. If the array can have multiple elements in real life then you'd need an outer loop around the code above to iterate through it.
2) If you're looping through the keys of an object, you don't need to also iterate through the properties a different way. You seemed to have two loops designed to do the same thing.
I am having a complex JSON object which I want to compare like below :
$scope.new = [
{
"name": "Node-1",
"isParent": true,
"text" : [
{
"str" : "This is my first Node-1 string",
"parent":[]
},
{
"str" : "This is my second Node-1 string",
"parent":[]
}],
"nodes": [
{
"name": "Node-1-1",
"isParent": false,
"text" : [
{
"str" : "This is my first Node-1-1 string",
"parent":[]
},
{
"str" : "This is my second Node-1-1 string",
"parent":[]
}],
"nodes": [
{
"name": "Node-1-1-1",
"isParent": false,
"text" : [
{
"str" : "This is my first Node-1-1-1 string",
"parent":[]
},
{
"str" : "This is my second Node-1-1-1 string",
"parent":[]
}],
"nodes": []
}
]
}
]
}
]
But while comparing I want to ignore 1 property also but as I am using Angular.js I don't see any option in angular.equal which will omit that property while comparing 2 object.
console.log(angular.equals($scope.new,$scope.copy));
So while doing research I came with below answer which is using lodash having emit option but problem is I guess omit create a copy and I guess I will have performance degradation in case of lodash.
Exclude some properties in comparison using isEqual() of lodash
So now I am thinking to convert object so string and then do comparison and I guess that will be fast but problem is how I will omit that property while string comparison?
Something like this:
var str1 = JSON.stringify(JSON.stringify($scope.new));
var str2 = JSON.stringify(JSON.stringify($scope.copy));
console.log(str1==str2);
Note: I want to ignore isParent property while comparing 2 object.
What would be the best way to do compare 2 object?
Converting to strings is not the best approach in these cases.
Keep them as objects.
Using loadash:
const propertiesToExclude = ['isParent'];
let result = _.isEqual(
_.omit(obj1, propertiesToExclude),
_.omit(obj2, propertiesToExclude)
);
Using plain AngularJS, create a copy of the objects removing the not needed properties and then compare them:
let firstObj = angular.copy(obj1);
let secondObj = angular.copy(obj2);
const propertiesToExclude = ['isParent'];
function removeNotComparatedProperties(obj) {
propertiesToExclude.forEach(prop => {
delete obj[prop];
});
}
removeNotComparatedProperties(firstObj);
removeNotComparatedProperties(secondObj);
angular.equals(firstObj, secondObj);
You can use lodash and override the standard comparator used for deep comparison if you use _.isEqualWith:
var objA = {
isParent: true,
foo: {
isParent: false,
bar: "foobar"
}
};
var objB = {
isParent: false,
foo: {
isParent: true,
bar: "foobar"
}
};
var comparator = function(left, right, key) {
if (key === 'isParent') return true; // if the key is 'isParent', mark the values equal
else return undefined; // else fall back to the default behavior
}
var isEqual = _.isEqualWith(objA, objB, comparator);
console.log(isEqual); // true
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
To exclude multiple properties, extend the comparator function accordingly:
var comparator = function(left, right, key) {
if (key === 'isParent' || key === 'anotherKey') return true;
else return undefined;
}
You could also use a number of different approaches syntactically, depending on what you prefer -- a switch statement, an array that you iterate...
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" }];
I tried using _.uniq, but I guess because { "a" : "1" } is not equal to itself, it doesn't work. Is there any way to provide underscore uniq with an overriden equals function?
.uniq/.unique accepts a callback
var list = [{a:1,b:5},{a:1,c:5},{a:2},{a:3},{a:4},{a:3},{a:2}];
var uniqueList = _.uniq(list, function(item, key, a) {
return item.a;
});
// uniqueList = [Object {a=1, b=5}, Object {a=2}, Object {a=3}, Object {a=4}]
Notes:
Callback return value used for comparison
First comparison object with unique return value used as unique
underscorejs.org demonstrates no callback usage
lodash.com shows usage
Another example :
using the callback to extract car makes, colors from a list
If you're looking to remove duplicates based on an id you could do something like this:
var res = [
{id: 1, content: 'heeey'},
{id: 2, content: 'woah'},
{id: 1, content:'foo'},
{id: 1, content: 'heeey'},
];
var uniques = _.map(_.groupBy(res,function(doc){
return doc.id;
}),function(grouped){
return grouped[0];
});
//uniques
//[{id: 1, content: 'heeey'},{id: 2, content: 'woah'}]
Implementation of Shiplu's answer.
var foo = [ { "a" : "1" }, { "b" : "2" }, { "a" : "1" } ];
var x = _.uniq( _.collect( foo, function( x ){
return JSON.stringify( x );
}));
console.log( x ); // returns [ { "a" : "1" }, { "b" : "2" } ]
When I have an attribute id, this is my preffered way in underscore:
var x = [{i:2}, {i:2, x:42}, {i:4}, {i:3}];
_.chain(x).indexBy("i").values().value();
// > [{i:2, x:42}, {i:4}, {i:3}]
Using underscore unique lib following is working for me, I m making list unique on the based of _id then returning String value of _id:
var uniqueEntities = _.uniq(entities, function (item, key, a) {
return item._id.toString();
});
Here is a simple solution, which uses a deep object comparison to check for duplicates (without resorting to converting to JSON, which is inefficient and hacky)
var newArr = _.filter(oldArr, function (element, index) {
// tests if the element has a duplicate in the rest of the array
for(index += 1; index < oldArr.length; index += 1) {
if (_.isEqual(element, oldArr[index])) {
return false;
}
}
return true;
});
It filters out all elements if they have a duplicate later in the array - such that the last duplicate element is kept.
The testing for a duplicate uses _.isEqual which performs an optimised deep comparison between the two objects see the underscore isEqual documentation for more info.
edit: updated to use _.filter which is a cleaner approach
The lodash 4.6.1 docs have this as an example for object key equality:
_.uniqWith(objects, _.isEqual);
https://lodash.com/docs#uniqWith
Try iterator function
For example you can return first element
x = [['a',1],['b',2],['a',1]]
_.uniq(x,false,function(i){
return i[0] //'a','b'
})
=> [['a',1],['b',2]]
here's my solution (coffeescript) :
_.mixin
deepUniq: (coll) ->
result = []
remove_first_el_duplicates = (coll2) ->
rest = _.rest(coll2)
first = _.first(coll2)
result.push first
equalsFirst = (el) -> _.isEqual(el,first)
newColl = _.reject rest, equalsFirst
unless _.isEmpty newColl
remove_first_el_duplicates newColl
remove_first_el_duplicates(coll)
result
example:
_.deepUniq([ {a:1,b:12}, [ 2, 1, 2, 1 ], [ 1, 2, 1, 2 ],[ 2, 1, 2, 1 ], {a:1,b:12} ])
//=> [ { a: 1, b: 12 }, [ 2, 1, 2, 1 ], [ 1, 2, 1, 2 ] ]
with underscore i had to use String() in the iteratee function
function isUniq(item) {
return String(item.user);
}
var myUniqArray = _.uniq(myArray, isUniq);
I wanted to solve this simple solution in a straightforward way of writing, with a little bit of a pain of computational expenses... but isn't it a trivial solution with a minimum variable definition, is it?
function uniq(ArrayObjects){
var out = []
ArrayObjects.map(obj => {
if(_.every(out, outobj => !_.isEqual(obj, outobj))) out.push(obj)
})
return out
}
var foo = [ { "a" : "1" }, { "b" : "2" }, { "a" : "1" } ];
var bar = _.map(_.groupBy(foo, function (f) {
return JSON.stringify(f);
}), function (gr) {
return gr[0];
}
);
Lets break this down. First lets group the array items by their stringified value
var grouped = _.groupBy(foo, function (f) {
return JSON.stringify(f);
});
grouped looks like:
{
'{ "a" : "1" }' = [ { "a" : "1" } { "a" : "1" } ],
'{ "b" : "2" }' = [ { "b" : "2" } ]
}
Then lets grab the first element from each group
var bar = _.map(grouped, function(gr)
return gr[0];
});
bar looks like:
[ { "a" : "1" }, { "b" : "2" } ]
Put it all together:
var foo = [ { "a" : "1" }, { "b" : "2" }, { "a" : "1" } ];
var bar = _.map(_.groupBy(foo, function (f) {
return JSON.stringify(f);
}), function (gr) {
return gr[0];
}
);
You can do it in a shorthand as:
_.uniq(foo, 'a')
We have MongoDB docs that look like this:
var JavascriptObject = {
DbDocs : [
{
_id : "1",
{..more values..}
},
{
_id : "2",
{..more values..}
},
{
_id : "3",
{..more values..}
}
]
}
Based on certain values in the JavascriptObject, we order an array of the _id from the documents, and the result is this:
var OrderedArray = [ 2, 1, 3 ];
Right now, we're rebuilding the entire JavascriptObject by matching the _id in the OrderedArray with the _id in DbDocs:
var JavascriptObjectToRebuild = [];
var DbDocuments = JavascriptObject.DbDocs;
var DocumentCount = 0;
for (var OrderedNumber in OrderedArray) {
for (var Document in DbDocuments) {
if ( DbDocuments[Document]._id === OrderedArray[OrderedNumber] ) {
JavascriptObjectToRebuild[DocumentCount] = {}; // new Document Object
JavascriptObjectToRebuild[DocumentCount]._id = DbDocuments[Document]._id;
JavascriptObjectToRebuild[DocumentCount]...more values = DbDocuments[Document]...more values;
DocumentCount++; // increment
}
}
}
var SortedJavascriptObject = { DbDocs: [] }; // format for client-side templating
for (var Document in JSONToRebuild) {
SortedJavascriptObject.DbDocs.push(JavascriptObjectToRebuild[Document]);
}
Is there a faster more efficient way to sort the JavascriptObject based on this OrderedArray?
See update below if it's impossible to sort directly and you have to use OrderedArray instead.
If you can apply your criteria within the callback of the Array#sort function (e.g., if you can do it by comparing two entries in the array to one another), you can simply sort JSON.DbDocs directly.
Here's an example that sorts based on the numeric value of _id; naturally you'd replace that with your logic comparing objects.
Also note I've changed the name of the top-level variable (JSON is kinda in use, and in any case, it's not JSON):
var Obj = {
DbDocs : [
{
_id : "2",
more: "two"
},
{
_id : "1",
more: "one"
},
{
_id : "3",
more: "three"
}
]
};
Obj.DbDocs.sort(function(a, b) {
return +a._id - +b._id; // Replace with your logic comparing a and b
});
document.querySelector('pre').innerHTML = JSON.stringify(Obj, null, 2);
<pre></pre>
If it's impossible to sort directly and you have to work from OrderedArray, then it's still possible with sort, but it's less elegant: You use Array#indexOf to find out where each entry in the array should be:
Obj.DbDocs.sort(function(a, b) {
return OrderedArray.indexOf(+a._id) - OrderedArray.indexOf(+b._id);
});
(The + converts the IDs from strings to numbers, since OrderedArray contains numbers in your question, but the ID values are strings.)
Live Example:
var Obj = {
DbDocs : [
{
_id : "1",
more: "one"
},
{
_id : "2",
more: "two"
},
{
_id : "3",
more: "three"
}
]
};
var OrderedArray = [2, 1, 3];
Obj.DbDocs.sort(function(a, b) {
return OrderedArray.indexOf(+a._id) - OrderedArray.indexOf(+b._id);
});
document.querySelector('pre').innerHTML = JSON.stringify(Obj, null, 2);
<pre></pre>
If there are going to be lots of entries in OrderedArray, you might want to make a lookup object first, to avoid lots of indexOf calls (which are costly: (georg did that in an answer, but he's since deleted it for some reason)
var OrderMap = {}
OrderedArray.forEach(function(entry, index) {
OrderMap[entry] = index;
});
Obj.DbDocs.sort(function(a, b) {
return OrderMap[a._id] - OrderMap[b._id];
});
(We don't need to convert the IDs to numbers because property names are always strings, so we've converted the numbers to strings when building the map.)
Live Example:
var Obj = {
DbDocs : [
{
_id : "1",
more: "one"
},
{
_id : "2",
more: "two"
},
{
_id : "3",
more: "three"
}
]
};
var OrderedArray = [2, 1, 3];
var OrderMap = {}
OrderedArray.forEach(function(entry, index) {
OrderMap[entry] = index;
});
Obj.DbDocs.sort(function(a, b) {
return OrderMap[a._id] - OrderMap[b._id];
});
document.querySelector('pre').innerHTML = JSON.stringify(Obj, null, 2);
<pre></pre>
As I understood, you want to get result like so,
[{"_id":"2"}, {"_id":"1"}, {"_id":"3"}]
so you can do it with one forEach and indexOf, like so
var JSONDADA = {
DbDocs : [{_id : "1",}, {_id : "2"}, {_id : "3"}]
};
var DbDocuments = JSONDADA.DbDocs;
var OrderedArray = [ 2, 1, 3 ];
var result = [];
DbDocuments.forEach(function (el) {
var position = OrderedArray.indexOf(+el._id);
if (position >= 0) {
result[position] = el;
}
});
console.log(JSON.stringify(result));
303 see other
......
Convert OrderedNumber into a hash _id => position:
sorter = {}
OrderedNumber.forEach(function(_id, pos) {
sorter[_id] = pos
})
and then sort the target array by comparing id's positions:
DbDocuments.sort(function(a, b) {
return sorter[a._id] - sorter[b._id];
})
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;
}