I'm trying to remove an object from Json Object it works..but it replace it with null..i dont know why, how can i remove the null value from the json..heres the function :
company.deleteExternalLinkFromGrid = function (row, matricule) {
// console.log('Inside of deleteModal, code = ' + code);
//$scope.sitting= {};
console.log(matricule);
//console.log(JSON.stringify(linkJsonObj));
delete linkJsonObj[matricule];
console.log(JSON.stringify(linkJsonObj));
};
heres the object:
[{"name":"xxx","link":"www.ddd.com","id":0,"$$hashKey":"uiGrid-001Z"},null,null]
You can use filter(), x will be without null's.
function test()
{
var x =[{"name":"xxx","link":"www.ddd.com","id":0,"$$hashKey":"uiGrid-001Z"},null,null].filter(isNotNull);
alert(JSON.stringify(x));
}
function isNotNull(value) {
return value != null;
}
fiddle
There are multiple ways to delete an object from an array of objects in JavaScript. You don't need AngularJS for that, you can use VanillaJS.
If you just want the nulls filtered you can use
var yourArray =[{"name":"xxx","link":"www.ddd.com","id":0,"$$hashKey":"uiGrid-001Z"},null,null];
yourArray = yourArray.filter(function(elt){
return elt != null;
});
But this loses the original reference to your object.
If you want to keep the reference, Use array.splice().
yourArray.forEach(function(){
yourArray.splice(yourArray.indexOf(null),1);
});
now you will have null less array in yourArray. This actually deletes an object from an array without changing the reference,
delete will replaced the object with undefined
You can filter the array to remove them using Array#filter()
var array = [{
"name": "xxx",
"link": "www.ddd.com",
"id": 0,
"$$hashKey": "uiGid-001Z"
}, {
"name": "xx",
"link": "www.dddcom",
"id": 1,
"$$hashey": "uiGrid-0029"
}, {
"name": "xxx",
"link": "www.ddd.com",
"id": 2
}];
delete array[1];
array = array.filter(a=>a);
console.log(JSON.stringify(array));
Related
I am having a array of objects which looks like this
var data = [
{
"id": "K014-s1",
"status": true,
"amount": 992,
"check": true,
},
{
"id": "K014-s2",
"status": false,
"amount": 10992,
"check": true,
}
]
I want only certain key values from the object in the array
Required Output:
var data = [
{
"id": "K014-s1",
"amount": 992,
},
{
"id": "K014-s2",
"amount": 10992,
}
]
Code I tried:
var filteredData = []
var result = data.map((obj) => {
filteredData.push(obj.id)
})
console.log(filteredData)
I tried. But don't Know how to make it. Please Help me with some solutions
instead of pushing object to another array,you can simply map your data like this
var result = data.map((obj) => {
return {
id:obj.id,
amount:obj.amount
}
})
Array.prototype.map already creates a new array, so result will already be the new value you are looking for.
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
var filteredResult = data.map((obj) => {
//additional logic, if needed here.
return {
id: obj.id,
amount: ob.amount,
}
})
Alternatively you can of course use a for loop or array.prototype.forEach to achieve the same:
var filteredData = []
data.forEach((obj) => {
filteredData.push({
id: obj.id,
amount: ob.amount,
})
})
No need to initiate a new array because the map method returns a new array what you can do is map the array then delete the property or method that you want then return the new array. Here's a simple solution that you use for your reference
const filteredData = data.map(newData => {
delete newData.status
delete newData.check
return newData
})
Simply you can loop over array using forEach method and delete key, value pairs. For example data.forEach((obj) => { delete obj.status; delete obj.check; }) since array is a reference type you can easily mutate it and not create a duplicate of data.
I have json data like this.
var obj= {
"id": "6",
"name": "parent",
"path": "/",
"category": "folder",
"fid":"6"
"children": [
{
//some values
},
{
//some other values
}
]
}
how to iterate and push it into an new array.
type declaration
getEntry: Array<Object> = []
pushing into an array method
get addedEntry() {
let files = []
this.getEntry = files.push(this.obj)
}
But, i am getting type error. How to push this object into an array or make it array.?
The push method returns a Number representing the new value of the array. That's why you are getting a TypeError (you are assigning a Number to an Array of Objects).
You should do the following instead.
get addedEntry() {
let files = []
files.push(this.obj)
this.getEntry = files
}
Here's the docs entry for the push method in JavaScript.
I need to push a new ID for my data array. If I try pushing into data it creates one more object but not adding into the array for each.
Data:
[{"devices":{"dID":"TLSM01"},"uuid":"e863c776-f939-4761-bbce-bf0501b42ef7"},
{"devices":{"dID":"TLSM01"},"uuid":"5a0cd70d-891d-48d8-b205-e92e828ac445"}]
Data need to be added:
{"EntityID":"12458412548"}
Final Result:
[{"devices":{"dID":"TLSM01","EntityID":"12458412548"},"uuid":"e863c776-f939-4761-bbce-bf0501b42ef7"},
{"devices":{"dID":"TLSM01","EntityID":"12458412548"},"uuid":"5a0cd70d-891d-48d8-b205-e92e828ac445"}]
Code:
var data = [{
"devices": {
"dID": "TLSM01"
},
"uuid": "e863c776-f939-4761-bbce-bf0501b42ef7"
}, {
"devices": {
"dID": "TLSM01"
},
"uuid": "5a0cd70d-891d-48d8-b205-e92e828ac445"
}]
data.push({
"EntityID": "test"
});
console.log(data);
data is an array containing objects. If you want to add a property to each object you have to iterate over the array.
You need to add a new property to the object devices which is not an array thus you cannot use .push()
var data = [{"devices":{"dID":"TLSM01"},"uuid":"e863c776-f939-4761-bbce-bf0501b42ef7"},{"devices":{"dID":"TLSM01"},"uuid":"5a0cd70d-891d-48d8-b205-e92e828ac445"}];
data.forEach(d=>d.devices['EntityID']="test");
console.log(data);
If your "final result" is the result you want to achieve, you don't want to push anything. You're just setting a new property on the entries that already exist in the array. So, loop through and do that:
data.forEach(function(entry) {
entry.EntityID = "12458412548";
});
(Or a simple for loop.)
If you're using ES2015+ syntax, you could use an arrow function:
data.forEach(entry => entry.EntityID = "12458412548");
...or a for-of loop:
for (const entry of data) {
entry.EntityID = "12458412548";
}
DEMO
var jsonObj = [{"devices":{"dID":"TLSM01"},"uuid":"e863c776-f939-4761-bbce-bf0501b42ef7"},
{"devices":{"dID":"TLSM01"},"uuid":"5a0cd70d-891d-48d8-b205-e92e828ac445"}];
jsonObj.map(item => item.devices["EntityID"] = "12458412548");
console.log(jsonObj);
I'm new to software Field. i have a json array of objects like
var treeObj = [
{
"name": "sriram",
"refernce_id": "SAN001",
"sponer_id": "SAN000"
},
{
"name": "neeraja",
"refernce_id": "SAN002",
"sponer_id": "SAN001"
},
{
"name": "upender",
"refernce_id": "SAN003",
"sponer_id": "SAN001"
},
{
"name": "manoj",
"refernce_id": "SAN004",
"sponer_id": "SAN002"
},
{
"name": "shirisha",
"refernce_id": "SAN005",
"sponer_id": "SAN002"
},
{
"name": "ragu",
"refernce_id": "SAN006",
"sponer_id": "SAN003"
},
{
"name": "santhu",
"refernce_id": "SAN007",
"sponer_id": "SAN003"
}
];
Here i will pass the above object to a function. in that function i need to compare reference id with sponer_id in every object and if they are equal we need to push them into an Array which we call as child object just like below and again we need to check in the child Array that the reference id in is present in sponer_id of above object if it is present again we need to push them to child array into object which contains the reference_id. the final array Object looks like.
[
{
"name": "sriram",
"parent": null,
"children": [
{
"name": "neeraja",
"parent": "sriram",
"children": [
{
"name": "manoj",
"parent": "neeraja"
},
{
"name": "shirisha",
"parent": "neeraja"
}
]
},
{
"name": "upender",
"parent": "sriram",
"children": [
{
"name": "ragu",
"parent": "neeraja"
},
{
"name": "santhu",
"parent": "neeraja"
}
]
}
]
}
]
Here sriram's reference id of treeObj is present as sponer id in neeraja and upender object. so neeraja and upender becomes child to sriram. and neeraja's reference_id is present as sponer_id in manoj and shirisha objects of treeObj. simultaneously the child can many more child objects and we need to format the object dynamically.
The function which i wrote looks like
var mainArr = [], subArrs = [], subObj={}, subIds = [], find = "SAN001";
formatData(treeObj);
function formatData(treeObj){debugger;
var arr = [];
for(var x=0; x<= treeObj.length-1; x++){debugger;
var sampData = treeObj[x];
if(find == sampData.sponer_id){
arr.push(sampData.refernce_id);
subArrs.push(sampData);
}
}
subIds.push(arr);
console.log(subIds);
console.log(subArrs);
formatData(subArrs);
}
please guide me where i went wrong. thanks in advance.
//1. find all items the have no parent and push them on a stack like so:
let stack = treeObj.reduce((list, item) => {
if (<ids match>) list.push(item);
return item;
}, []),
let result = [].concat(stack);
//2. while loop the stack:
while (stack.length > 0) {
let item = stack.shift();
item.children = treeObj.reduce((list, child) => {
if (<ids match>) {
list.push(child);
}
return list;
}, []).map(child => {
child.parent = item;
stack.unshift(item);
return child;
});
}
return result;
UPDATE
So in »good old JS« and with some improvements:
var stack = treeObj.filter(function (item) {
return item.<parent_id> === item.<child_id> });
var result = [].concat(stack);
while (stack.length > 0) {
var item = stack.shift();
item.children = treeObj.filter(function (child) {
return item.<id> === child.<parent_id>;
});
item.children.forEach(function (child) { stack.unshift(child) });
}
Basically:
find the root(s) and save them on the stack
while.length > 0
shift() the first item from the stack
find all children of that item and unshift them on the stack
Done
Adding a parent property to the items, or removing unneeded one, can be done in the loop. The whole thing can also be done using recursion, but I once ran in the »too much recursion error« by doing such stuff, so I prefer an iterative approach. And of course, instead of .reduce, .filter and .forEach, you can use regular loops, but I prefer a functional style. All in all, no matter how you do it, it is not that difficult, just find the elements to start with and then repeat with all of their children and so on. Withing the while loop all children are found, or, the whole subtree with that element as root.
Good luck!
You're basically trying to convert an array to a n-ary tree.
Entering your original tree function into formatData gives you an array (arr) with the referenceIDs of all objects having SAN001 as parent and another array (subArrs) with all children of with sponerId SAN001.
You then store the arr in subIds, log subIds and subArr and proceed to call format data on subArrs recursively. Then you check on subArr which objects have "SAN001 as predecessor" (which should be all objects at that time) and push that object in subArr. If im not getting it wrong this leads to an infinite loop.
Starting points for improvements:
you're "find" variable does not change, it's hardwired to "SAN001" - this would maybe be okay for your first trip when you're 100% sure that the root object has always this referenceID. But in the second trip, you want to check which objects depend on a second level element, so you need to set find to an corresponding referenceId.
Your subArrs contains all objects depending on SAN001. But in the second and following trips, you don't want to get childrens of SAN001 but child of objects in the subArr. So you need to travers old objects finding children of objects in subArr instead of traversing subArr seeking children of SAN001.
Hope that clear's it up a little bit.
A hint for further research: You're basically trying to "convert an array into a n-ary tree" with javascript.
I have a JSON object with two arrays of an object x.
I'm using angularJS and I want to add/edit/delete objects in the JSON (just like the Angular TODO app example on angular.org).
Is there a way to create a new empty (with the structure of x but no values) JSON object of x, and simply push that to the above JSON object array?
How do I go about creating an empty value JSON object of x?
My Sample object x is (I nullified all the values) pasted below. So my JSON is just an array of these objects. In Angular, I want the user to fill out a form and hold the data in an empty object of this type and push it to the array. That's my goal.
Sample JSON
[{
"id": null,
"title": "",
"date": {},
"billPayerId": null,
"notes": "Sample Notes",
"billFinances": {
"billPayerId": null,
"billItemEntry": [
{
"itemDescriptionId": 1,
"itemDescription": "",
"userIdAndLiableCost": [
{
"userId": null,
"liableCost": null
},
{
"userId": null,
"liableCost": null
}
]
},
{
"itemDescriptionId": null,
"itemDescription": "",
"userIdAndLiableCost": [
{
"userId": null,
"liableCost": null
},
{
"userId": null,
"liableCost": null
}
]
}
],
"billTotal": null
},
"groupId": null
}];
You can use an object literal to store whatever you want. It is just a bag of properties (i.e. name) and values. e.g. var order = {};
Then an array literal could be used to hold the orders. e.g var orders = []; orders.push(order); But it would be just as easy to use another object literal with the id as a property.
But it seems like you want some sort of validation. Perhaps something to manage the order data and handle the validation, etc. Like so:
orderManager.dataStore = {
_data: {},
//_redundantData = []; //could easily store in an array if id isn't unique
get: function (id) {
return this._data[id];
},
getAll: function () {
return this._data;
},
set: function (id, order) {
validateOrder(order);
this._data[id] = order;
},
clear: function (id) {
this._data[id] = undefined;
},
add: function (order) {
validateOrder(order);
this._data[order.id] = order;
},
assertNotNull: function (data, key) {
if(data[key] == undefined) {
throw new Error("Key Missing: " + key + " for " + data.name);
}
},
validateOrder: function(order) {
assertNotNull(order,"id");
assertNotNull(order,"title");
//etc
},
containsOrder: function (id) {
for(var i=0;i<array.length;i++) {
if(array[i].id === id) {
return true;
}
}
return false;
}
};
If I'm reading all of this right, I think you may be misunderstanding how Angular works. You don't have to create an empty object for Angular to use within a form. As long as your form's inputs use dot notation, it will generate the object for you as the user fills in the inputs with data.
E.g.
<form>
<input type="text" ng-model="myForm.name">
<input type="text" ng-model="myForm.email">
<input type="text" ng-model="myForm.nickname">
</form>
Since we used the dot notation in the ng-model attribute, it creates the object for us as the user fills out the form. The generated object would look like this after the inputs are completed:
$scope.myForm = {
name: 'Justin',
email: 'justin#email.com',
nickname: 'Cerebrl'
};
Now, normally once the user clicks save, you'd send the data to the server for persistence and you could then just empty the object (e.g. $scope.myForm = {};) to reset the form. But, for some reason, you want to build an array first, then send the whole thing to the server when fully complete (at least that's how I'm understanding it).
To do this, you have to get around the fact that Objects and Arrays in JavaScript are reference types, so you can't push the object full of data to an array, and then empty the object to reset the form as that would then empty the object within the array as well, blowing your data store.
I would personally address this problem with Angular's object copy method (e.g. angular.copy(source);) seen here: http://docs.angularjs.org/api/angular.copy This allows you to make a non-referenced copy of an object and use it without mutating the original object. So, within the "save function", you would have this:
var myNewObj = angular.copy($scope.myForm);
myDataArray.push(myNewObj);
$scope.myForm = {};
That way, you've saved the completed form data, pushed it to the array and cleared the form's input data. Does this answer your question?