Manipulate Json String Jquery - javascript

Supposed that I have this JSON STRING that is stored in a vairable:
{"name":"Joene Floresca"},{"name":"Argel "}
How can I make it
["Joene", "Argel"]

You mention you have a string. Use JSON.parse for that. Also, make sure it is an array. Afterwards, you can manually iterate through each object in the array and push the value
var str = '[{"name": "Joene Floresca"},{ "name": "Argel "}]';
var objA = JSON.parse(str);
var values = [];
for (var i = 0; i < objA.length; i++) {
for (var key in objA[i]) {
values.push(objA[i][key]);
}
}
console.log(values);

Assuming your JSON is an array, you can use map:
// Your JSON string variable
var jsonString = '[{"name":"Joene Floresca"},{"name":"Argel "}]';
// Parse the JSON to a JS Object
var jsObject = $.parseJSON(jsonString);
// Use map to iterate the array
var arr = $.map(jsObject, function(element) {
// Return the name element from each object
return element.name;
});
console.log(arr); // Prints ["Joene Floresca", "Argel "]
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You can iterate over objects inside array and store the names in a second array.
var data = JSON.parse('[{"name":"Joene Floresca"},{"name":"Argel "}]');
var names = [];
data.forEach(function(model) {
names.push(model.name);
});
// names now contains ["Joene Floresca", "Argel"]
alert(names);

Related

How to remove partial duplicate values in jquery array

I have a single level array of key/value pairs, like this:
var user_filters= ['color=blue', 'size=small', 'shape=circle', 'size=large', 'shape=square']
I need a function to perform the following:
find all duplicate keys
replace the first occurrence of the key/value pair with the second occurrence
delete the second occurrence
In this case, it would produce the following result:
user_filters= ['color=blue', 'size=large', 'shape=square']
Something like...
function update_array(){
$.each(user_filters, function(i){
var key = this.split('=')[0];
if(key is second occurrence in user_filters)
{
var index = index of first occurrence of key
user_filters[index] = user_filters[i];
user_filters.splice(i,1);
}
});
}
What is the best way to do this? Thanks!
I would keep the data in an object and this way any duplicate will automatically overwrite the previous entry..
See this for example:
var user_filters= ['color=blue', 'size=small', 'shape=circle', 'size=large', 'shape=square'];
var object = {};
for (var i = 0; i < user_filters.length; i++) {
var currentItem = user_filters[i].split('=');
var key = currentItem[0];
var value = currentItem[1];
object[key] = value;
}
console.log(object);
You can use a hash object to get the key-value pairs without duplicates and then transform the hash object back into an array like this:
function removeDuplicates(arr) {
var hash = arr.reduce(function(h, e) {
var parts = e.split("=");
h[parts[0]] = parts[1];
return h;
}, {});
return Object.keys(hash).map(function(key) {
return key + "=" + hash[key];
});
}
var user_filters = ['color=blue', 'size=small', 'shape=circle', 'size=large', 'shape=square'];
console.log(removeDuplicates(user_filters));
You could use a Map which does the unique/overriding automatically, and is able to get you an array back in case you need it
var user_filters= ['color=blue', 'size=small', 'shape=circle', 'size=large', 'shape=square'];
var m = new Map(user_filters.map(v => v.split("=")));
console.log([...m.entries()].map(v => v.join("=")));
It would be better to iterate from back of array ,
thus for every unique key you need to keep a variable true or false (initially false).
so if true mean already occurred so deleted it else keep it and make its variable true .
It is much more better approach then your current . you don't have to keep last index and swapping then deleting.
You may convert to json and then back to the array format you want . IN the below code you get the result object in the format you want.
var user_filters= ['color=blue', 'size=small', 'shape=circle', 'size=large', 'shape=square'];
function toJson(obj){
var output = {};
$.each(obj, function(i){
var keyvalPair = this.split('=')
var key = keyvalPair[0];
output[key]= keyvalPair[1];
});
return output;
}
function toArray(obj){
var output = [];
$.each(obj, function(i){
output.push(i+"="+obj[i]);
});
return output;
}
var result = toArray(toJson(user_filters));
console.log(result);

Convert a JSON Object to Comma Sepearted values in javascript

I have a JSON OBJECT
{"data":{"source1":"source1val","source2":"source2val"}}
which i want to convert into
data : source1val, source2val.
Use Object.keys with Array#map
The Object.keys() method returns an array of a given object's own enumerable properties.
The map() method creates a new array with the results of calling a provided function on every element in this array.
var input = {
"data": {
"source1": "source1val",
"source2": "source2val"
}
};
var output = Object.keys(input.data).map(function(k) {
return input.data[k];
}).join(',');
console.log(output); //manipulated object
console.log(input); //Original object
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
var input = {
"data": {
"source1": "source1val",
"source2": "source2val"
}
};
var output = [];
var i;
for (i = 0; i < input.data.length; i++) {
output.push(input.data[i]);
}

Store variable from loop as array to localStorage

What's the way to store result of the for loop as array to localStorage? That is, the result should be: ["./somepage1.html", "./somepage2.html"].
<div class="someclass" href="./somepage1.html">foo</div>
<div class="someclass" href="./somepage2.html">foo</div>
<script>
var foo = document.getElementsByClassName("someclass");
for (var i = 0; i < foo.length; i++)
{
var hrefs = foo[i].getAttribute("href");
console.log(hrefs);
}
</script>
First, create the Array of hrefs.
This uses Array.prototype.map to create a new Array of hrefs from the HTMLCollection of Elements.
var foo = document.getElementsByClassName("someclass");
var arr = Array.prototype.map.call(foo, function(elem) {
return elem.getAttribute("href");
});
Then serialize it using JSON.stringify(), and store it wherever you want in localStorage.
localStorage.foobar = JSON.stringify(arr);
Of course, JSON isn't required to store your data. You can serialize it however you want.
You could have used .join() instead to create a comma-separated string.
var foo = document.getElementsByClassName("someclass");
localStorage.foobar = Array.prototype.map.call(foo, function(elem) {
return elem.getAttribute("href");
}).join(",");
Though this isn't the specific result you described.

Convert Array of Javascript Objects to single simple array

I have not been able to figure out how to properly accomplish this.
I have a JS array of objects that looks like this:
[{"num":"09599","name":"KCC","id":null},{"num":"000027","name":"Johns","id":null}]
I would like to convert this into a simple, single JS array, without any of the keys, it should look like this:
[
"09599",
"KCC",
"000027",
"Johns" ]
The IDs can be dropped entirely. Any help would be really appreciated.
Simply iterate the original array, pick the interesting keys and accumulate them in another array, like this
var keys = ['num', 'name'],
result = [];
for (var i = 0; i < data.length; i += 1) {
// Get the current object to be processed
var currentObject = data[i];
for (var j = 0; j < keys.length; j += 1) {
// Get the current key to be picked from the object
var currentKey = keys[j];
// Get the value corresponding to the key from the object and
// push it to the array
result.push(currentObject[currentKey]);
}
}
console.log(result);
// [ '09599', 'KCC', '000027', 'Johns' ]
Here, data is the original array in the question. keys is an array of keys which you like to extract from the objects.
If you want to do this purely with functional programming technique, then you can use Array.prototype.reduce, Array.prototype.concat and Array.prototype.map, like this
var keys = ['num', 'name'];
console.log(data.reduce(function (result, currentObject) {
return result.concat(keys.map(function (currentKey) {
return currentObject[currentKey];
}));
}, []));
// [ '09599', 'KCC', '000027', 'Johns' ]
You can use Object.keys() and .forEach() method to iterate through your array of object, and use .map() to build your filtered array.
var array = [{"num":"09599","name":"KCC","id":null},{"num":"000027","name":"Johns","id":null}];
var filtered = array.map(function(elm){
var tmp = [];
//Loop over keys of object elm
Object.keys(elm).forEach(function(value){
//If key not equal to id
value !== 'id'
//Push element to temporary array
? tmp.push(elm[value])
//otherwise, do nothing
: false
});
//return our array
return tmp;
});
//Flat our filtered array
filtered = [].concat.apply([], filtered);
console.log(filtered);
//["09599", "KCC", "000027", "Johns"]
How about using map :
var data = [
{"num":"09599","name":"KCC","id":null}
{"num":"000027","name":"Johns","id":null}
];
var result = data.map(function(obj) {
return [
obj.num,
obj.name,
obj.id
];
});

How to convert Javascript array to JSON string

I have an array called values which has this data
var values=new Array();
values.push("english":"http://www.test.in/audio_ivrs/sr_listenglishMSTR001.wav");
values.push("kannada":"http://www.test.in/audio_ivrs/sr_listfrenchMSTR001.wav");
When I do JSON.stringify(values) I get values with square brackets, but I need a JSON string a shown below with urllist appended at the first.
{
"urlList":{
"english":"http://www.test.in/audio_ivrs/sr_listenglishMSTR001.wav",
"kannada":"http://www.test.in/audio_ivrs/sr_listfrenchMSTR001.wav"
}
}
Your code as you've defined it will give you errors. This is not valid JavaScript; you can't create an array element like this.
values.push("english":"http://www.test.in/audio_ivrs/sr_listenglishMSTR001.wav");
If you want the structure you've specified in your question then you'll need to use a nested object rather than an array to contain the key/value pairs.
var values = {
urlList: {}
};
values.urllist.english = "http://www.test.in/audio_ivrs/sr_listenglishMSTR001.wav";
values.urllist.kannada = "http://www.test.in/audio_ivrs/sr_listfrenchMSTR001.wav";
DEMO
HOWEVER...
Let's assume for a moment that what you meant to code was this (note the curly braces):
var values=new Array();
values.push({"english":"http://www.test.in/audio_ivrs/sr_listenglishMSTR001.wav"});
values.push({"kannada":"http://www.test.in/audio_ivrs/sr_listfrenchMSTR001.wav"});
This would tell me that you're pushing objects into an array which is perfectly valid JavaScript.
To get this information from the array into the structure you need you can use something like this loop:
var out = {
urlList: {}
};
for (var i = 0, l = values.length; i < l; i++) {
var el = values[i];
var key = Object.keys(el);
var value = el[key];
out.urlList[key] = value;
}
JSON.stringify(out);
DEMO

Categories

Resources