Json iteration fails when there is one sub object - javascript

I'm converting an xml string to json using php and then posting it to a
javascript file where I try to iterate it. When the object contains more than one object, json contains an array of objects like the first sample and I can iterate using the .length function but when the object contains only 1 object an array is not being created and the .length function fails. How can I make the iteration work in both cases without knowing the object's name?
Sample 1:
{"class":[
{
"name":"history",
"grade":"10"
},
{
"name":"chemistry",
"grade":"8"
}
]
}
Sample 2:
{"class":
{
"name":"history",
"grade":"10"
}
}

You could check length, and if it's undefined it means it's just an object, then you make it an array with just one element:
if collection.length == undefined:
collection = [collection]
# the rest of the code doesn't need to be changed

You can use for for that and you don't need length
var test = {"class":[
{
"name":"history",
"grade":"10"
},
{
"name":"chemistry",
"grade":"8"
}
]
}
for (var i in test){
console.log(test[i]);
}

You can check to see if the object is an array first: Array.isArray(obj) . If it isn't then you know you don't need to iterate it.
var obj = {"class":[
{
"name":"history",
"grade":"10"
},
{
"name":"chemistry",
"grade":"8"
}
]
}
if (!Array.isArray(obj)) return obj;
// else iterate it.

You have to know the data type of the variable before knowing how to use .length properly.
var dataTypeLength;
var data = {
"class":
{
"name":"history",
"grade":"10"
}
}
if (Array.isArray(data.class)) {
dataTypeLength = data.class.length;
} else {
dataTypeLength = Object.keys(data.class).length;
}
console.log(dataTypeLength);

Related

Find if key or value exist in the array's nested objects

I have an array of nested objects.
const data = [
{
audi: {
model_Q3: 'Q3',
model_A3: 'A3'
}
},
{
mercedes: {
model_GLA: 'GLA',
model_GLC: 'GLC'
}
}
];
I want a function to return true if the nested object's (audi, mercedes) key or value equals/includes the parameter.
function findCar(parameter) {
let exists = false;
data.forEach(cars => {
Object.entries(cars).map(([_, carValues]) => {
console.log(carValues)
});
});
}
findCar('model_Q3') //true;
findCar('model_') //true;
findCar('GLA') // true;
findCar('GL') // true;
Thanks.
Since you're working with a simple object the JSON.stringify method should come quite handy here. It constructs a json string that contains the entire object, and therefore all the keys and values you have in your object. With that string you can extract every key or value by a regex match.
This is how it may look like:
function findCar(parameter) {
const keysAndValues = JSON.stringify(data).match(/"([^"]+)"/g);
for (let entry of keysAndValues) if (entry.includes(parameter)) return true;
return false;
}
The regex here matches for every entry that starts with ", then only characters that are not " and followed by a ".

Javascript - Inserting unique elements in Array: Multidimensional check x Temporary unidimensional array

I don't know if it's a stupid question, but here it comes:
Imagine an array of unordered objects like:
[{id:4, name:"a"},{id:2, name:"b"},{id:3, name:"ee"},{id:1, name:"fe"},.....].
This array is dinamically created inside a loop using javascript, but, everytime I'll push something to the array I must check if an object with the same id exists and only pushs the newones.
Which one is faster:
1) At every loop check manualy the entire array.
or
2) Create a temporary unidimensional array only with ids and use indexOf to check if the new object id is present and then, if not present at the temporary array, add it to the original array.
How about
var a = []
var o = { id:10, name:"xyz" }
if(typeof a[o.id]=="undefined") {
a[o.id] = { name:o.name }
}
? That should be fastest for most machines. Or to not change your object structure
a[o.id] = { id:o.id, name:o.name }
But the better approach would be
function getA(i) { if (typeof a[i] == "undefined") return null;
return { id:i, name:a[i].name }; }

Get object properties and values from array using lodash/underscore.js

Fiddle Example
I have an array like this:
var array = [ {
'data-price': '0.00',
'data-term': '532',
'data-model_id': '409',
},
{
'data-price': '0.00',
'data-term': '483',
'data-model_id': '384',
},
{ text: 'dffdfddgfdgf' } ];
I want to filter out the last object and extract [{data-model_id:409},{data-model_id:384}] from the first two objects. I have tried this code:
var k = _(array).filter('data-model_id').pluck('data-model_id').value();
console.log(k);
and it returns an array of the values only, ["409", "384"] . Is there a function to return the whole objects in lodash or underscore?
Using plain JS to show the logic: you need to filter out the elements that don't have the key, then map the new collection to another form:
array.filter( function(item){
return 'data-model_id' in item;
}).map( function( item ){
return { 'data-model_id' : item['data-model_id'] }
});
http://jsfiddle.net/dn4tn6xv/7/
What if I told you this is possible using just native javascript? Just use Array.filter and Object.keys, using the former to filter and the latter to get the keys and then returning a Boolean by comparing the index of the Array returned by Object.keys
var k = array.filter(function(obj){
return Object.keys(obj).indexOf("data-model_id") > -1;
});
In lodash you can do like this:
get full object
console.log(_.filter(array, 'data-model_id'));
get only data-model_id property
var res = _.chain(array).filter('data-model_id').map(function (el) {
return _.pick(el, 'data-model_id');
}).value();
Example

how iterate through this json object (not with jquery) [duplicate]

This question already has answers here:
How do I iterate over a JSON structure? [duplicate]
(13 answers)
Closed 8 years ago.
I would like to iterate through a json object which I got from var jsonObj json_encode( <?php echo $php_array ?>);. This looks to me like a different format to what most people have. For example, w3schools shows this as a json object:
{
"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
}
Mine seems to have completely structure:
{"PINEFOREST JEWELRY":
["3034.25","2002-01-02"],
"AMBERS DESIGN":
["2034.75","2002-01-02"],
"ELEGANT JEWELERS":
["206","2002-01-02"],
"SALEM'S JEWELERS":
["406","2002-01-02"]}
Am I able to iterate through this?
You can use a for loop to iterate through the object's direct properties as follows:
var val;
for(var key in obj) {
if(obj.hasOwnProperty(key)){
val = obj[key];
console.log(val);
}
}
You can use a for in with a nested for
for (var key in data) {
for (var i = 0; i < data[key].length; i++) {
console.log(data[key][i]);
}
}
Yes you can itterate through it as it is valid json.
To start of you need to convert the json into something javascript can itterate over, which you can do with JSON.parse() (MDN). Im assuming that the 'json' you described above is a string of 'json' so:
var jewellery = JSON.parse(myJson); // replace myJson with whatever variable is holding your json
At this point you have an object which you can itterate over. One of the easiest ways to do this would be by using Object.keys() (MDN) and Array.forEach() (MDN) like so:
Object.keys(jewellery).forEach(function (key) {
console.log(key); // would log 'PINEFOREST JEWELRY' the first time
jewellery[key].forEach(function (price) {
console.log(price); // Should log '3034.25' the first time
}
});
Give that a try, otherwise you could still use the other solutions other people have submitted, either or would work. This is how I would do it though!!

Create nested Json in js

I want to create Json like this:
{
"name":"name",
"children":[
{
"childName":"name"
},
{
"childName":"name"
}
]
}
I don't know how to place none-named property in json obj and place and obj into "children".
OK, if you mean key itself is variable then you cannot create json-object in single shot,
you will have to create it using '[]' notation
var myObj = {};
myObj[myProp1] = [] //or some value or some json/map again
myObj[myProp2] = 'hi'
myProp1 and myProp2 are variables.if you can explain your problem in more detail then you will get more clear answer.
If you ask how to manipulate that JSON object, then maybe this would help.
Your original object:
var object = {
"name":"name",
"children":[
{
"childName":"name"
},
{
"childName":"name"
}
]
};
1) How to place none-named property in json obj.
Object is not array, so should assign key/value, though either or both of them were empty. You can insert using dot or like array assignment.
object.country = "Malaysia";
object[""] = "No Keys";
object["novalue"] = "";
2) How to place an obj into "children".
var aNewChild = {
"childName": "Handsome one"
};
object.children.push(aNewChild);

Categories