How to retain the duplicate values during the JSON stringify operation - javascript

I am obtaining the response from the server in JSON format. This JSON may constitute objects with duplicate Keys. When I was displaying the result the duplicate key values were getting committed. After debugging I found out that this is happening because of the JSON.stringify method that I am performing to format the code before providing to the front-end.
As of now when I perform the JSON.stringify then it removes the duplicate entries and provides only the last value for the duplicate keys however I would like to retain everything.
var obj = {name: "John", age: 30, name: "New York"};
var result = JSON.stringify(obj).replace(/\_/g, '');
console.log(result);
//{"name":"New York","age":30}
As we can see the first name has been committed. How to modify the code so we can retain all values of the duplicated key?
Please Note:
As of now, I have provided the sample code that has the duplicate key name. However, when I am getting the response from the server I am unaware of what key might be duplicated so I am looking for a general solution that can work for everything rather than hard-coded logic that works only for name.
Any suggestions or workarounds would be really appreciated.

Json objects don't allow duplicated keys.
If you execute just:
var obj = {name: "John", age: 30, name: "New York"};
console.log(obj)
You will see that you have already lost the first "name" value.
The only work around that I can think of, is to never transfor the received JSON String to an Object.
Or you can manually write a logic to split this json string by commas, and transform it into a JSON object according to you need, but without duplicated keys, for example:
{name: ["John", "New York"], age: 30};

Related

Javascript/node.js retrieving value from dictionary key which is in a 2d array

I've never asked a question on here but here goes.
Lets say I have an array (named whatever) that looks like this when displayed:
[[{name: "Joe", price: 42}],[{name: "Smith", price: 34}],[{name: "Jerry", price: 67}]]
And I want to do something like whatever[1].price (this fails in my program) I want to be able to take one of the arrays in whatever and retrieve it like whatever[1].price. Any way to do this similar to an ArrayName[index].key ?
first, your JSON is not correct, see the updated one;
since inner element of array is an array with single item so you can access it with 0 index.
var test = [[{name: "Joe", price: 42}],[{name: "Smith", price: 34}],[{name: "Jerry", price: 67}]];
test.forEach(item=> {
console.log(item[0]['price'])
});
Why does an Array of Objects be stored in an another array? Just remove the extra array initialization if you just want to achieve this
And I want to do something like whatever[1].price
Change the data like this:
[{name: "Joe", price: 42}],[{name: "Smith", price: 34}],[{name: "Jerry", price: 67}]
If you can't change the data, then A.T.'s solution will suffice
Well, based on your response ( which have an unnecessary array which contain an array of objects ) you can access to your data like
whatever[0][0].price
The better way is to change your response in backend to get an array of objects then you can access it like normal
whatever[0].price

JavaScript remove string from a value within an object

I have an object:
let Data = {name: 'Flomo', age: 25, address: 'Sinkor', id: 'NMF25'}
I want to console log the entire object but the id value should only contain the last three characters.
Like this:
{name: 'Flomo', age: 25, address: 'Sinkor', id: 'F25'}
I'm doing this:
console.log(Data.replace(/NM/g, ''))
But I got:
TypeError: Data.replace is not a function
Is there an easy way to achieve this?
replace is a method that operates on String, and doesn't change the string in-place.
If you're not worried about changing the original data, you can do this:
let Data = {name: 'Flomo', age: 25, address: 'Sinkor', id: 'NMF25'}
Data.id = Data.id.replace('NM', '')
console.log(Data);
Alternatively, if you're not sure what the first characters of the id will be (or how many there could be), you could do this:
let Data = {name: 'Flomo', age: 25, address: 'Sinkor', id: 'NMF25'}
Data.id = Data.id.substring(Data.id.length-3)
console.log(Data);
If you need to keep the original data intact, you can copy the object, however this can be complicated depending on the data that might be in the object: How do I correctly clone a JavaScript object?
The replace function works on a String. Youre calling that function on an Object.
You probably intended to call replace on the value of the property id. The terms I just used should help you mentally step thru problems like this in the future!
If you look at MDN's documentation for JavaScript, you'll see which functions you can call on which Types and other objects.

How to access an attribute from a JSON line saved in a position from an array?

This may be a very simple question but I really can't seem to make it work.
I have several JSON lines and a notes array.
Using notes.push(JSONline) I am saving one JSON line per array position, I assume, so in the following manner:
//notes[1]
{"id":"26","valuee":"20","datee":"2016-04-05T15:15:45.184+0100","id2":51}
//notes[2]
{"id":"27","valuee":"134","datee":"2016-04-05T15:15:47.238+0100","id2":53}
//notes[3]
{"id":"26","valuee":"20","datee":"2016-04-05T15:15:45.184+0100","id2":52}
Here is my problem: I want to print one specific attribute, for example id from one specific JSON line in the array. How can I do this?
When I do console.log(notes) it prints all the JSON lines just as expected. But if I do console.log(notes[1]) it prints the first character of the JSON line in that position, not the whole line.
Similarly console.log(notes[1].id) does not print the id from the first JSON line, in fact it prints 'undefined'.
What am I doing wrong?
Thank you so much.
I'd recommend that you parse all the json when you are pushing to notes, like:
notes.push(JSON.parse(JSONLine))
If you are somehow attached to having json strings in an array instead of objects, which I wouldn't recommend, you could always just parse once you have the jsonLine id
JSON.parse(notes[id]).id
Basically, you want to use JSON.parse for either solution and I'd strongly recommend converting them to objects once at the beginning.
You need to remember that JSON is the string representation of a JS object. JS strings have similar index accessor methods to arrays which is why you can write console.log(notes[0]) and get back the first letter.
JavaScript doesn't allow you to access the string using object notation, however, so console.log(notes[0].id) will not work and the reason you get undefined.
To access the data in the string using this method you need to parse the string to an object first.
var notes = ['{"id":"26","valuee":"20","datee":"2016-04-05T15:15:45.184+0100","id2":51}'];
var note0 = JSON.parse(notes[0]);
var id = note0.id;
DEMO
This leaves the question of why you have an array of JSON strings. While it's not weird or unusual, it might not be the most optimum solution. Instead you could build an array of objects and then stringify the whole data structure to keep it manageable.
var obj0 = {
"id": "26",
"valuee": "20",
"datee": "2016-04-05T15:15:45.184+0100",
id2: 51
};
var obj1 = {
"id": "27",
"valuee": "134",
"datee": "2016-04-05T15:15:47.238+0100",
"id2": 53
}
var arr = [obj0, obj1];
var json = JSON.stringify(arr);
OUTPUT
[
{
"id": "26",
"valuee": "20",
"datee": "2016-04-05T15:15:45.184+0100",
"id2": 51
},
{
"id": "27",
"valuee": "134",
"datee": "2016-04-05T15:15:47.238+0100",
"id2": 53
}
]
You can then parse the JSON back to an array and access it like before:
var notes = JSON.parse(json);
notes[0].id // 26
That's because you have {"id": "value"... as a string in your key value pairs. "id" is a string so you can't reference it like a property. 1. use
var notes = JSON.parse(notes);
as mentioned in the comments by The alpha
or remove the quotes try
{id:"26", ...}
that's why notes[i].id is returning undefined

Store object/array in jQuery Cookie

How can I store an object/array in JavaScript Cookies?
I tried that simple code
var item = {
price: 200,
company: 'Microsoft',
quantity: 500,
code: 'm33'
}
console.log(item);
Cookies.set('item', item);
console.log(Cookies.get('item'));
It shows all the values in the first console message, but gives only "[object Object]" in the second. Looks like js-cookie cannot work with objects correctly. Is there any way I can fix that?
You are storing an object, and cookies are allowed text-only. Remember that cookies have a max-length of 4 KB, so you can't store a lot of information here (use localStorage instead).
To solve this problem, you must to stringify the json first:
Cookies.set('item', JSON.stringify(item));
And you'll store a stringified object. To access it then, you must to parse the string:
console.log(JSON.parse(Cookie.get('item')));
Just use:
Cookies.getJSON('item')
js-cookie has built-in support for JSON parsing as from version 2.0.0, there is no need to change how you set it. For more information, see https://github.com/js-cookie/js-cookie/tree/v2.1.0#json
In cookie you can only store string. So in order to store object first you convert your object into string. Using this plugin here is an example:
var people = [
{"id": 123, "name": "Mazahir Eyvazli"},
{"id": 128, "name": "Mayki Nayki"},
{"id": 131, "name": "Mike Shinoda"}
];
$.cookie("people", JSON.stringify(people));
If you want to access your people as an object from cookie
// $.cookie("people") will return people object as an string
// therefore we parse it to JSON object
var people = $.parseJSON($.cookie("people"));
// now we can access our object
people[0]["id"] // --> 123
people[1]["name"] // --> Mayki Nayki

Get value from Json object with unique key

How do I check if a JSON object have key are duplicate, just get distint the key and not use foreach function? Such as:
var objectData = {[value1: abc], [value1: abc], [value2: bcd]}
If a key doesn't exist, and I try to access it, will it return undefined? Or get the error?
If this is meant to be an array of JSON objects:
var objectData = [ {"value1": "abc"}, {"value1": "abc"}, {"value2": "bcd"} ];
Then your answer lies within the responses to this question: Remove duplicates from an array of objects in javascript or this one Remove duplicate objects from an array using javascript.
If your notation accurately reflects what is produced by your system (or your own coding), you may want to rework it a bit so it makes sense.
Hope that helps.

Categories

Resources