Extracting data from JsonArray using JS/jQuery - javascript

I have a JsonArray something like this.
var json_array = [{ "text": "id", "size": 4}, { "text": "manifesto", "size": 4}, { "text": "also", "size": 4}, { "text": "leasing", "size": 4}, { "text": "23", "size": 4}];
Is there anyway to get me all the "text" property of this json_array in another array using Javascript/jQuery?
like:
var t_array = ["id","manifesto","also"....]

You can use $.map() to project the relevant information from your existing array into a new one:
var t_array = $.map(json_array, function(item) {
return item.text;
});

var t_array = [];
for (var i=0; i< json_array.length; i++)
t_array.push(json_array[i].text);

I think you'll need to build t_array by looping through json_array

something like:
var t_array = [];
$.each(json_array,function(i,o) {
t_array.push(o.text);
})
http://jsfiddle.net/bouillard/2c66t/

Related

Javascript, remove property from one of two similar objects in array

Let's assume we have this data set:
var array = [
{
"name": "a",
"group": "a"
},
{
"name": "a",
"group": "a"
},{
"name": "b",
"group": "b"
},
{
"name": "b",
"group": "b"
},
{
"name": "c"
}
];
and I want to loop through the array to see if there are two objects have the same group value, then remove the second of them.
for(var i = 0 ; i<array.length;i++){
var a = array[i];
for(var j = 0; j< array.length;j++){
if(array[j].group == a.group){
var b = array[j];
// I need code here to remove property "group" from the variable b only
break;
}
}
}
the final results I want are:
var array2 = [
{
"name": "a",
"group": "a"
},
{
"name": "a"
},{
"name": "b",
"group": "b"
},
{
"name": "b"
},{
"name":"c"
}
];
NOTE: I tried delete array[j].group but it caused to remove both group property from both equal objects. How can I solve that?
You shouldn't compare same items, just shift indexes in inner loop:
var array = [{"name": "a", "group": "a"},
{"name": "a", "group": "a"},
{"name": "b", "group": "b"},
{"name": "b", "group": "b"},
{"name": "c"}];
for(var i = 0 ; i < array.length - 1; i++){
var a = array[i];
if(!a.group){
continue;
}
for(var j = i+1; j < array.length; j++){
var b = array[j];
if(b.group === a.group){
delete b.group;
}
}
}
console.log(array)
You can try this:
var tmpObj = {};
tmpObj.name = array[j].name;
array.splice(j, 1, tmpObj);
It should remove the element with index j and add new object with only name.
Just store all the group values you already have seen, and remove them if you see them again. Moreover, this will save you a loop.
var myArray = [...];
var existingGroups = [];
myArray.forEach(function(item){
if(item.group){
if(existingGroups.indexOf(item.group) === -1)
existingGroups.push(item.group);
else
delete item.group;
}
});
I'd go with a different approach:
Little explanation of the if condition:
array.slice(0, i): we take only the previous elements of the array.
.filter(v => v.group === val.group) we see if they have the same value for property group.
.length === 0) If there is at least one element with the same value of group, we do not enter the if and return only the name, otherwise we return the value itself
var array = [{"name": "a", "group": "a"},
{"name": "a", "group": "a"},
{"name": "b", "group": "b"},
{"name": "b", "group": "b"},
{"name": "c"}];
array = array.map((val, i) => {
if (array.slice(0, i).filter(v => v.group === val.group).length === 0) {
return val;
}
return {name: val.name};
})
console.log(array)
Here is a simple code which might help:
var groups = {};
array.forEach(function(o) {
if (groups[o.group]) {
delete o.group;
} else {
groups[o.group] = true;
}
})
You can also use more functional approach but you will need an additional utility library or have to implement some of the methods yourself.
var groups = array.map(function(o) { return o.group; }).unique();
groups
.map(function(group) {
return array.filter(function(o) { o.group == group }).slice(1);
})
.flatten()
.forEach(function(o) { delete o.group });
flatten & unique are not included in the JavaScript spec.
You don't need imbricated loops to do this. You can use .forEach() while keeping track of the groups that have been encountered so far. This can be done by using either the optional thisArg parameter or an explicit variable.
For instance:
var array = [
{ "name": "a", "group": "a" },
{ "name": "a", "group": "a" },
{ "name": "b", "group": "b" },
{ "name": "b", "group": "b" },
{ "name": "c" }
];
var grp = {};
array.forEach(function(o) {
grp[o.group] ? delete o.group : grp[o.group] = true;
});
console.log(array);

Compare array of objects to array of ids

Using jQuery, I would like to use an array of ids to find the objects inside the allObjects array that have the matching Id value.
var arrayOfIds = [1, 4, 5];
var allObjects = [{"Id":"1", "name":"aa"},{"Id":"2", "name":"bb"} ,{"Id":"3", "name":"cc"} ,{"Id":"4", "name":"dd"}, {"Id":"5", "name":"ee"}, {"Id":"6", "name":"ff"}, {"Id":"7", "name":"gg"}, {"Id":"8", "name":"hh"}, {"Id":"9", "name":"ii"}];
The result would equal:
[{"Id":"1", "name":"aa"}, {"Id":"4", "name":"dd"}, {"Id":"5", "name":"ee"}]
So far, I can only use the following to extract an individual object:
var result = $.grep(arrayOfIds, function(e) { return e.Id == 3; });
I feel as though the answer might be achieved by amending the above $.grep query somehow but can't figure it out.
You don't need jQuery for this. You can use Array.prototype.filter() to filter allObjects and Array.prototype.includes() to check if the objects Id property is in arrayOfIds:
allObjects.filter(x=> arrayOfIds.includes(Number(x.Id)))
See demo on JS Bin.
Best is you transform the array to an object itself:
function atoo(a)
{
var i, obj;
obj = {};
for (i = 0; i < a.length; i++)
{
obj[a[i].Id] = a[i];
}
return obj;
}
You can now access all items in the array through the object by simply addressing them as an index:
obj["4"]
returns the correct object that is also stored in the array under a[3].
There is no jQuery involved which should be considered a feature because it is a general solution to all kinds of these problems.
Using a filter (as in Array.prototype.filter()) is easier to write but also incurs in performance problems when you access the items very often or the array is very large. The above solution relies on the internal implementation of the object referencing which is as fast as you can wish for.
You can use filter() method like following.
var arrayOfIds = [1, 4, 5];
var allObjects = [{ "Id": "1", "name": "aa" }, { "Id": "2", "name": "bb" }, { "Id": "3", "name": "cc" }, { "Id": "4", "name": "dd" }, { "Id": "5", "name": "ee" }, { "Id": "6", "name": "ff" }, { "Id": "7", "name": "gg" }, { "Id": "8", "name": "hh" }, { "Id": "9", "name": "ii" }];
var result = $(allObjects).filter(function() { return arrayOfIds.indexOf(+this.Id) > -1 }).get();

JSON.parse(data) return [undefine]

data = {
"users": [
[{
"value": "01",
"text": "ABC XYZ"
}],
[{
"value": "02",
"text": "XYZ ABC"
}]
]
}
var jsonData = JSON.parse(data);
for (var i = 0; i < jsonData.users.length; i++) {
var userlist = jsonData.users[i];
alert(userlist.text)
}
This output: [undefine];
But i want to get [ABC XYZ] and [XYZ ABC].
So how can I get text or value from this array?
data is already a JavaScript object, so no need for the extra JSON.parse.
You are getting an undefined result because users is an array of arrays, rather than an array of objects.
Try accessing the userlist like this:
var userlist = data.users[0][i];
JSBin: https://jsbin.com/sifoyivayi/edit?html,js,output
Your object contains nested array. Try like following.
var data = { "users": [[{ "value": "01", "text": "ABC XYZ" }], [{ "value": "02", "text": "XYZ ABC" }]] };
for (var i = 0; i < data.users.length; i++) {
var userlist = data.users[i][0];
alert(userlist.text);
}
Try like this:
var data={"users":[[{"value":"01","text":"ABC XYZ"}],[{"value":"02","text":"XYZ ABC"}]]};
for (var i = 0; i < data.users.length; i++) {
var userlist = data.users[0][i];
alert(userlist.text);
}

Convert a two dimensional array into an array of objects

I have a two dimensional array, datas, that I want to convert to an array of objects.
The keys are in datas[0], I want to extract them, name, child, and size. and then append each attribute to it to get a master object. For some reason it overrides and is only showing one object when I try this?
var test = new Object();
for (i = 0; i < datas.length; i++){
var obj = new Object();
obj.name = datas[i][0];
obj.parent = datas[i][1];
obj.size = datas[i][2];
test.update(obj);
}
I would like the final result to be:
[
{"name": "Billy", "parent":"Ann", "size": "1"},
{"name": "Ben", "parent": "John", "size": "1"},
etc...
]
The datas array looks like:
[["Name", "Parent", "Size"], ["Billy", "Ann", "1"], ["Ben", "John", "1"] ... ]
You can't make an object without properties, so your desired result can't be achieved.
Assuming you want:
[
{"name": "Billy", "parent": "Ann", "size": "1"},
{"name": "Ben", "parent": "John", "size": "1"},
etc...
]
Try:
var test = [];
for(i = 0; i < datas.length; i++){
test.push({
name: datas[i][0],
parent: datas[i][1],
size: datas[i][2]
});
}
// do something with test
{
{"name": "Billy", "parent":"Ann", "size"="1"},
{"name": "Ben", "parent": "John", "size" = "1"}
}
is not correct json. curly braces mean - object, object must be presented in key:value form. There are two possible correct json of this kind:
array of objects
[
{"name": "Billy", "parent":"Ann", "size"="1"},
{"name": "Ben", "parent": "John", "size" = "1"}
]
deep structure
{
"Billy" {"parent":"Ann", "size"="1"},
"Ben" {"parent": "John", "size" = "1"}
}
to generate first variant
var res = []
for(i = 0; i<datas.length; i++){
var obj = new Object();
obj.name = datas[i][0];
obj.parent = datas[i][1];
obj.size = datas[i][2];
res.push(obj);
}
JSON.stringify(res);
to generate second variant
var res = new Object();
for(i = 0; i<datas.length; i++){
var obj = new Object();
obj.parent = datas[i][1];
obj.size = datas[i][2];
res.[datas[i][0]] = obj;
}
JSON.stringify(res);

jquery parsing json

This is the JSON output that I currently have:
[{"pk": 1, "model": "system.employees",
"fields": {"chi_name": "N/A", "eng_name": "Eli"}}]
I want the output to be
[{"label": "Eli", "value": "1"}]
how can I take the values of pk and eng_name from the JSON data and output it like above?
You can use jQuery.map:
var data = [{"pk": 1, "model": "system.employees",
"fields": {"chi_name": "N/A", "eng_name": "Eli"}}];
var new = $.map(data, function(index, item) {
return { label: item.fields.eng_name, value: item.pk };
});
var result = [{"pk": 1, "model": "system.employees", "fields": {"chi_name": "N/A", "eng_name": "Eli"}}]
var output = [{ "label" : result[0].fields.eng_name, "value": result[0].pk}]
//assuming your source obj is called 'source'
var num = source[0].pk;
var eng_name = source[0].fields.eng_name;
...then you can do whatever with them, like
var output = [];
output.push({"label":eng_name, "value":num});
Good luck!
Try -
var h = JSON.parse('[{"pk": 1, "model": "system.employees", "fields": {"chi_name": "N/A", "eng_name": "Eli"}}]');
var a = [];
a.push({"label": h[0].fields.eng_name, "value": h[0].pk+''})
alert(JSON.stringify(a))
NB You'll need to import this code - https://github.com/douglascrockford/JSON-js/blob/master/json2.js if your browser doesn't support JSON.parse and JSON.stringify
Demo - http://jsfiddle.net/ipr101/uwZVW/

Categories

Resources