How to delete particular nested json attribute - javascript

I want to delete __metadata where ever it appears .How to do that I searched this question but didn't get exact solution. hope you will help me out .
{
"__metadata":{
"uri":"asd",
"type":"DP_CART_SRV.DPCARTHeader"
},
"Dealer":{
"__metadata":{
"uri":"asd"
},
"CustomerNo":"",
"Name1":"",
"Name2":""
},
"Retailer":{
"__metadata":{
"uri":"asd"
},
"CustomerNo":"",
"Name1":"",
"Name2":""
},
"Cart":"0000000081",
"Type":"SH",
"CreatedOn":"/Date(1399420800000)/",
"ChangedOn":null,
"OrderId":"",
"OrderType":"",
"ReqDeliveryDate":"2014/05/31",
"OrderValue":"11.00",
"DocCurrency":"EUR",
"NetValue":"11.00",
"Freight":"0.00",
"Discount":"0.00",
"Tax":"0.00",
"Remarks":"Remarks",
"Items":{
"results":[
{
"__metadata":{
"uri":"asd"
},
"Cart":"0000000081",
"ItemNo":"000010",
"ProductID":"FAN_FG1",
"ItemDesc":"Finshed product FAN",
"Quantity":"1.000",
"Uom":"KAR",
"Price":"11.00",
"Currency":"EUR",
"Available":"",
"DeleteStatus":""
},
{
"__metadata":{
"uri":"",
"type":""
},
"DeleteStatus":"",
"Available":"",
"Currency":"",
"Price":"",
"Uom":"",
"Quantity":"",
"ItemDesc":"",
"ProductID":"",
"ItemNo":"",
"Cart":""
}
]
}
}

Here is a fun one. Not very obvious way how you can do it:
var result = JSON.parse(JSON.stringify(obj, function(key, value) {
return key !== '__metadata' ? value : undefined;
}));
It makes use of the replacer function JSON.stringify method accepts:
replacer
If a function, transforms values and properties encountered while stringifying; if an array, specifies the set of properties included in objects in the final string.
A detailed description of the replacer function is provided in the javaScript guide article Using native JSON.
However be aware that this is not intended JSON.stringify and JSON.parse usage. Also of course the result will no longer be the original object, but a new object.
Demo: http://jsfiddle.net/7Gj47/

I don't really know what you mean by "nested json attribute". The OP appears to be an object literal, which is the syntax used for JSON, however JSON is a string.
Anyhow, supposing you have JSON, it can be turned into an object using JSON.parse. You can then iterate over the object and remove any property with a certain name, and recursively remove properties from "nested" objects using a function like:
function removeProp(obj, propName) {
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
if (p == propName) {
delete obj[p];
} else if (typeof obj[p] == 'object') {
removeProp(obj[p], propName);
}
}
}
return obj;
}
So if you have JSON (i.e. text representing an object), you can remove all instances of a particular property using something like:
var jsonText = '{ ... }';
var obj = JSON.parse(jsonText);
removeProp(obj, '__metadata');
jsonText = JSON.stringify(obj);
The function could take a third parameter that specifies if it should check nested objects or not.

Related

Javascript reserved word and object

I'm making a dictionary of words, so there are 1,000,000+ words.
The problem comes when I need to store the word constructor. I know this is a reserved word in javascript, but I need to add it to the dictionary.
var dictionary = {}
console.log(dictionary ['word_1'])
//undefined, this is good
console.log(dictionary ['word_2'])
//undefined, this is good
console.log(dictionary ['constructor'])
//[Function: Object]
// this cause initialization code to break
How can I fix this? I could muck with the it like key=key+"_" but that seems bad. Is there anything else I can do?
Instead of using a JS object, you could use the built-in Map type which uses strings/symbols as keys and does not conflict with any existing properties.
Replace
var dictionary = {} with var dictionary = new Map()
Override the constructor key as undefined
According to the MDN Object.prototype page, the only thing that isn't hidden by the __fieldname__ schema is the "constructor field". Thus, you could just initialize your objects via { 'constructor': undefined }.
However, you would have to make sure that in your for .. in statements would filter out all keys with undefined as their value, as it would pick up constructor as a "valid" key (even though it wouldn't before you specifically set it to undefined). I.E.
for(var key in obj) if(obj[key] !== undefined) { /* do things */ }
Check for types when getting/setting
Otherwise, you could just check the type when you 'fetch' or 'store' it. I.E.
function get(obj, key) {
if(typeof obj[key] !== 'function') // optionally, `&& typeof obj[key] !== 'object')`
return obj[key];
else
return undefined;
}
I think you should store all words and translation of them in an array. When you need to translate a word, you can use find method of Array.
For example:
var dict = [
{ word: "abc", translated: "xyz" },
...
];
Then:
var searching_word = "abc";
var translation = dict.find(function (item) {
return item.word == searching_word;
});
console.log(translation.translated);
// --> xyz
To achieve expected result , use below option of using index to get value of any key value
var dictionary = {};
var dictionary1 = {
constructor: "test"
};
//simple function to get key value using index
function getVal(obj, val) {
var keys = Object.keys(obj);
var index = keys.indexOf(val);//get index of key, in our case -contructor
return obj[keys[index]]; // return value using indec of that key
}
console.log(getVal(dictionary, "constructor"));//undefined as expected
console.log(getVal(dictionary1, "constructor"));//test
console.log(dictionary["word_1"]);
//undefined, this is good
console.log(dictionary["word_2"]);
//undefined, this is good
codepen - https://codepen.io/nagasai/pen/LOEGxM
For testing , I gave one object with key-constructor and other object without constructor.
Basically I am getting the index of key first and getting value using index

Loop through JSON structure using javascript/jQuery

I want to loop through the JSON I have below with the given JavaScript
{
"jsonUrl": "/testUrl",
"data": {
"country":"US",
"company":"ABC",
"items":[
{
"id": "1",
"id2": "12345",
"total": 1
},
{
"id": "2",
"id2": "23456",
"total": 2
}
]
}
}
I've tried the following but I've had no luck.
for (var key in json) {
if (json.hasOwnProperty(key)) {
alert(json[key]);
}
}
When doing this, the alert displays [object][object]. I don't get the actual data inside the object.
Firstly, don't use alert to watch the contents of the object in this case. When you use alert and you pass object in it, interpreter use toString method on this object. And the result of it is [object Object] construction. You can use JSON.stringify there.
How exactly you parse json? You can do this with JSON.parse.
Also, to not check if object has property with hasOwnProperty method you can use Array.prototype.forEach:
yourArrayData.forEach(function () {
console.log(JSON.stringify(value));
});
Also you can use for-of (only ES6+):
for (let value of yourArrayData) {
console.log(JSON.stringify(value));
}
A better option is to use the Object.keys() function to get the keys, then iterate to get your info.
The JSON object you are trying to loop through is several levels deep, and therefore you can't simply iterate over the keys and take their values (which in this case are also objects with keys). Depending on what information you want to retrieve, you will have to act differently. If you know the structure in advance, you can iterate over theObject.data.items using a for loop, or if you simply want to get to the the end of the JSON object, you can set up a queue:
let queue = [jsonObject];
while (queue.length > 0) {
var objectToEvaluate = queue.shift();
for (var key in objectToEvaluate) {
if (objectToEvaluate.hasOwnProperty(key)) {
if (typeof objectToEvaluate[key] === 'object') {
queue.push(objectToEvaluate[key]);
}
else {
// do something with the objectToEvaluate[key]
}
}
}
}
There are a few things to look out for with a queue. If it's possible for circular references ({a: b, b: a}), then you will need to keep track of which 'nodes' have been checked already. There are also some false positives that go along with checking whether the typeof is an object. I'd suggest reading more up on queues enter link description here

Find index of object in array by key

I have an array of objects like so
myobj= [{"item1" : info in here},{"item2" : info in here}, {"item3" : info in here}]
I'm trying to modify one, but I only know its key. I need to pinpoint the item1 object so I can change its value (the values are random and I don't know them, so I can't rely upon them).
If I could just get the index of the item it would be pretty easy: myobj[index].value = "newvalue".
Maybe using the index isn't the best way, so if it isn't, I'm open to other ideas.
I was thinking I could try something like
myobj.objectVar
Where objectVar is the key I'm being passed (item1, for example), however this does not work, possibly because it's a variable? Is it possible to use a variable like this maybe?
If it helps, I'm using underscore.js as well.
Your guess at a solution doesn't work because you're not accessing the individual objects, you're accessing an array of objects, each of which has a single property.
To use the data in the format you've got now, you need to iterate over the outer array until you find the object that contains the key you're after, and then modify its value.
myobj= [{"item1" : info in here},{"item2" : info in here}, {"item3" : info in here}]
function setByKey(key, value) {
myObj.forEach(function (obj) {
// only works if your object's values are truthy
if (obj[key]) {
obj[key] = value;
}
});
}
setByKey('item1', 'new value');
Of course, the far better solution is to stop using an array of single-property objects, and just use one object with multiple properties:
myobj= {"item1" : info in here, "item2" : info in here, "item3" : info in here};
Now, you can simply use myObject.item1 = "some new value" and it will work fine.
You can write a function like,
function getElementsHavingKey(key) {
var objectsHavingGivenKey = [];
//loop through all the objects in the array 'myobj'
myobj.forEach(function(individualObject) {
//you can use 'hasOwnProperty' method to find whether the provided key
// is present in the object or not
if(individualObject.hasOwnProperty(key)) {
// if the key is present, store the object having the key
// into the array (many objects may have same key in it)
objectsHavingGivenKey.push(individualObject);
}
});
// return the array containing the objects having the keys
return objectsHavingGivenKey;
}
If you only want to get the index of elements having the given key
You can do something like this,
function getIndexesOfElementsHavingKey(key) {
var objectsHavingGivenKey = [];
//loop through all the objects in the array 'myobj'
myobj.forEach(function(individualObject, index) {
//you can use 'hasOwnProperty' method to find whether the provided key
// is present in the object or not
if(individualObject.hasOwnProperty(key)) {
//push index of element which has the key
objectsHavingGivenKey.push(index);
}
});
// returns the array of element indexes which has the key
return objectsHavingGivenKey;
}
Try this code:
function changeObj( obj, key, newval )
{
for( var i=0, l=obj.length; i<j; i++)
{
if( key in obj[i] )
{
obj[i] = newval;
return;
}
}
}
var myObjArray= [{"item1" : "info in here"},{"item2" : "info in here"}, {"item3" : "info in here"}]
To find and add new value to the object inside an array:
myObjArray.forEach(function(obj) {
for(var key in obj) {
// in case you're matching key & value
if(key === "item1") {
obj[key] = "update value";
// you can even set new property as well
obj.newkey = "New value";
}
}
});
You can access objects the same using their index, even the object inside the original object.
Is this kind of what your looking for:
var otherObj = [{"oitem":"oValue"}];
var myobj= [{"item1" : otherObj},{"item2" : "2"}, {"item3" : "tesT"}];
myobj[0].item1[0].oitem = "newvalue";
alert(myobj[0].item1[0].oitem);

How to remove null values from javascript object

I have a javascript object that contains two arrays. Sometimes one of the arrays may be empty. I'm trying to loop through the object via a recursive function but I don't want any arrays that are empty or empty strings to enter the loop. What I have so far is producing the error Typeerror: obj.filter is not a function.
NOTE: obj is in this example has two arrays inside of it, but really, it could be anything that I pass into the function.
var obj = {
selected: [ "value1", "value"2],
unselected: []
}
function clearAndSetSelectElement($elem, obj, isEmpty) {
if(isEmpty) $elem.empty(); //empty the select element if it isn't empty
$.each(obj.filter(function(v){return v != null}), function() { //filter out empty arrays or empty strings
if(this instanceof Array) clearAndSetSelectElement($elem, this, false); //if this is an array make recursive call
$elem.append("<option />").val(this).text(this)); //append value to select element
});
}
obj.filter is not a function, but obj.selected.filter should be (obj is an object, not an array).
It won't work in IE7 by default I guess, you'll either have to copy the polyfill from Mozilla Developer's Network (MDN) or use Modernizr.
May be you can try this (if you want to populate a select with some options from an array)
HTML
<select id="sel"></select>​
JS
function setSelect(elem, obj)
{
for(var o in obj)
{
if(obj[o] instanceof Array && obj[o].length)
{
$.each(obj[o], function(key, value) {
elem.append($("<option></option>").attr("value",value).text(value));
});
}
}
}
Populate the selct using setSelect function
var obj = {
selected: [ "value1", "value2"],
unselected: []
}
var elem=$('#sel');
setSelect(elem, obj);
DEMO.

Retrieve by value from an Object?

This must be a duplicate, but I've been Googling "retrieve by value from object javascript" and "javascript lookup object by value" and every variant and got nowhere, so apologies and here goes.
Say I have a JavaScript object like this:
var options = {"ford": "red", "citroen": "blue"};
How do I do look up value blue to get citroen back?
There's always the 'write your own function' route, I guess:
function returnbyValue(options, v):
for (var prop in options) {
if (options.hasOwnProperty(v)) {
if (options[prop] === v) {
return prop;
}
}
}
return null;
but does JavaScript have anything inbuilt, or is there a neater way to do this?
The property of an object can be accessed just like an associative array!
This worked like a charm!
var obj = {
'key': 'val'
};
alert( obj['key'] );
Alternatively, if you wish to use a method you can create a prototype method.
Object.prototype.getPropertyByString = function( str ) {
return this[str];
};
alert( obj.getPropertyByString( 'key' ) );
Edit: Wow I just noticed I failed to answer your question, my apologies! Allow me to get a second chance.
There is no built in function, but my script below works!
var obj = {
'key': 'val'
};
Object.prototype.getKeyByValue = function( object ) {
for(var key in this) {
if(this.key === object) {
return key;
}
}
return null;
};
alert( obj.getKeyByValue( 'val' ) );
It loops through the object and returns the key if it matches a value. This wil work, no matter if the value is an int, string, object, anything. This is because I've used the strict equal comparison ("===") which also checks if the object type is the same.
Also, please note that checking if the property exists is silly if you're looping through all keys of the object anyway. Obviously, when you're looping through all keys, they exist.
There is no such built-in method. And your own function looks good to me. I can't figure out any improvement of it.

Categories

Resources