Iterate through object values - javascript - javascript

Given this data structure:
{ "name": [ "can't be blank" ], "league_id": [ "You already have a team in this league." ] }
How can I print this?
Can't be blank
You already have a team in this league
So basically I want to iterate through the values of the object. How can I do this with Javascript? Thank You!

Your data structure doesn't make much practical sense in that your property values are arrays with just one element in them. While legal, for the data you are showing, it makes more sense just to have the strings as the values.
Either way, a for/in loop over the object will allow you to iterate the keys.
With current structure:
let obj = {
"name": ["can't be blank"],
"league_id": ["You already have a team in this league."]
};
for(var key in obj){
console.log(obj[key][0]); // Here, you have to index the property value, which is an array
}
With arrays removed:
let obj = {
"name": "can't be blank",
"league_id": "You already have a team in this league."
};
for(var key in obj){
console.log(obj[key]); // Here, you can access the key value directly
}
You can also use Object.keys(obj), along with a .forEach() method call, which is a newer technique:
let obj = {
"name": ["can't be blank"],
"league_id": ["You already have a team in this league."]
};
Object.keys(obj).forEach(function(key){
console.log(obj[key][0]); // Here, you have to index the property value, which is an array
});

Let's see:
const obj = { "name": [ "can't be blank" ], "league_id": [ "You already have a team in this league." ] }
console.log(Object.values(obj).map(value => value.toString()).join("\n"))
Get values of the keys in object with Object.values method
map over them
Since the value itself is Array, cast it to string (or get the first element)
Join them with a new line

Related

How to return the key of an array of objects using its name

NOTE: I know what I'm attempting to do logically doesn't make sense in terms of why I want to achieve this, however I just want to know if it's possible and if so what I might be writing wrong?
I'm working with an array of objects like so:
this.animalsAndFruits = [
{
"category": "Apple",
"num1": 1287,
"num2": 12956
},
{
"category": "Panda",
"num1": 2574,
"num2": 25826
},
....
]
This may seem tedious and rather ridiculous however using the array I want to return the word 'category', not the value just the key 'category'.
I've tried
this.objectFromArray[0].category
However it only returns the value of the 0th indexed item (even though the 0th indexed item key will always have key 'category')
Is there another way I can accomplish this?
P.S. The reason why I want to get 'category' is because I need to set a variable = 'category', however I don't want to hardcode it directly like this
var someVar = 'category'
If it helps, the value in the key:value pair where the key = category is always a string (whereas all of the other values under different keys are numbers.
Maybe logic like so might work =>
if(value = string) then return key ?
Since the non-category properties have a consistent format (num#, right? at least going by the prior question), if you want to find the key which does not start with num, you can use Object.keys to get an array of keys, then .find the key matching the condition:
const animalsAndFruits = [
{
"category": "Apple",
"num1": 1287,
"num2": 12956
},
{
"category": "Panda",
"num1": 2574,
"num2": 25826
},
];
const propertyName = Object.keys(animalsAndFruits[0]).find(
key => !key.startsWith('num')
);
console.log(propertyName);
If you happen to be able to depend on the non-num key always being the first one defined in the objects, you could also use Object.keys(animalsAndFruits[0])[0].

Improper array handling by jQuery: length= 0 bug?

I don't know if this is my little knowledge of jQuery or it is just a bug, but here's what happens. I have this small piece of JSON code
{
"planes":[
{
"id":1,
"name":"Boeing 767-300",
"height":54.9 ,
"wingspan":47.6,
"vel": 851,
"vel max":913,
"plane width":283.3,
"weight":86070,
"full weight":158760,
"passengers":{
"1 class":350,
"2 class":269,
"3 class":218
},
"fuel tank":90.625,
"engine":"2 turbofan General Electric CF6-80C2"
},
{
"id":2,
"name":"Boeing 737-800",
"height":33.4 ,
"wingspan":35.8,
"vel": 840,
"vel max":945,
"plane width":105.44,
"weight":32704,
"full weight":56472,
"passengers":{
"1 class":189
},
"fuel tank":90.625,
"engine":"2 turbofan CFM56-3C1"
}
]
}
which I'm then getting with jQuery's getJSON without any flaw. Then I want two separate arrays: one holding the keys and the other holding the values, and again no problem with Object.keys and Object.values. By logging the result in a single string, everything is fine. Until I try to construct an associative array using keys as indexes and values as data. By logging the result, I get an extra "length" index with value "0". here's my jQuery code
var arr=[];
$.getJSON("js/jsondata.json", function(data){
var keys= Object.keys(data.planes[0]);
var values= Object.values(data.planes[0]);
//im only testing on the first object, for now
$.each(keys, function(i){
//creating the associative index and assigning the value
arr[keys[i]]= values[i];
console.log("Key: "+ keys[i]+", Value: "+values[i]);
//this logs the exact values and indexes
});
console.log(arr);
//this logs an extra "length" 0
});
What you really want to use is a key-value object and not an array. So you have at least to options:
Actually the arrays are objects, and you will be able to attach/add new properties, however, this kind of objects have a pre-defined prototype and properties. One of these properties is length. Cause that, you're getting an "unexpected" property length.
Changing this var arr = []; to this var arr = {};.
Changing this var arr = []; to this var arr = Object.create(null);.
Adding properties to an object array
let arr = [2];
arr['myKey'] = 'EleFromStack';
console.log(arr.myKey);
console.log(arr.length); // 1 cause length is part of Array type.
Adding properties to a key-value object
let arr = {}; // Object.create(null);
arr['myKey'] = 'EleFromStack';
console.log(arr.myKey);
console.log(arr.length); // undefined cause length is not part of the Object type.
Biggest problem is there's no such beast as associative arrays in JavaScript. All arrays must have numbered indices. Association the way you want is handled with objects.
So, you can just assign the first plane in your planes array to a variable and retain your original association rather than iterate it.
Is there a particular reason you're trying to disassemble and reassemble your object to an array this way?

Parsing JSON keys into array of strings [duplicate]

This question already has answers here:
Get array of object's keys
(8 answers)
Closed 4 years ago.
I am currently trying to handle a GET request that returns a body in application/json structured like this:
{
"items": {
"item001": {"id":1234, "name": "name001"},
"item002": {"id":1235, "name": "name002"},
"item003": {"id":1236, "name": "name003"}
}
}
I'm trying to get an array of strings that looks like
array = ["item001", "item002", "item003"];
I don't care about any of the underlying hierarchy, I just need the key of each object as an array. I've tried several different methods (map(), JSON.stringify(), etc) but I can't seem to index each key in a array[i] format.
In fact, each time I try to even print the name of a single key, for example
var obj = JSON.parse({'whole json here'});
print(obj.items[1]);
I get an [object Object] error, which makes sense as obj.items is not indexed with a key other than "item001" for example. However, I do not know what the key for each object will be, hence the need for an array of the keys. Thank you in advance!
You can do Object.keys.It will return an array of the keys of an object
var x = {
"items": {
"item001": {
"id": 1234,
"name": "name001"
},
"item002": {
"id": 1235,
"name": "name002"
},
"item003": {
"id": 1236,
"name": "name003"
}
}
}
var y = Object.keys(x.items);
console.log(y)
You can use Object.keys(). For Reference
var obj={"items":{"item001":{"id":1234,"name":"name001"},"item002":{"id":1235,"name":"name002"},"item003":{"id":1236,"name":"name003"}}};
var result = Object.keys(obj.items);
console.log(result);
Object.keys will do that.
var obj = JSON.parse({'your json'});
console.log( Object.keys(obj.items) );

Displaying all keys value pair of array in nested json javascript

I have a JSON data from a URL and c am consuming it using jQuery ajax method.
Now as the JSON code below shows I have a DATA array containing objects in my JSON, now if I access FirstName using resp.DATA[0].FirstName, I am able to get it, but now I have to display all the key value pairs in DATA array and i don't know the key name i.e. I have to show every key and value.
There are two customers on data.
How can I do it either using JavaScript or jQuery?
JSON DATA:
{
"ERROR": [],
"DATA": [{
"CustomerID": "124",
"BranchID": "12",
"FirstName": "sandeep",
"LastName": "b",
"EmailID": "gggg#gmail.com",
"Sex": "Male",
"Landline": "",
"AlternateNumber": "",
"Password": "5735c2801",
"USERVARCHAR_2": ""
}],
"META": {
"totalPages": "1",
}
}
I have to display Key and value of each customer data in the form KEY:VALUE, so please suggest me how to loop this.
Use the for loop to iterate over javascript array literal
for (var key in resp.DATA) {
// skip loop if the property is from prototype
if (!resp.DATA.hasOwnProperty(key)) continue;
var objct = resp.DATA[key];
for (var prop in objct) {
// skip loop if the property is from prototype
if(!objct.hasOwnProperty(prop)) continue;
// your code
alert("The key is "+prop + "and the value is " + objct[prop]);
}
}
References:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty
Use Object.keys(object_name) to fetch all the keys of a Object.
The Object.keys() method returns an array of a given object's own
enumerable properties, in the same order as that provided by a
for...in loop (the difference being that a for-in loop enumerates
properties in the prototype chain as well).
for(var cust of resp.DATA){ // To iterate a array
for(var key in cust){ // To iterate a object ennumerable properties
console.log("Key is: "+key+" and Value is: "+cust[key]);
}
}
do this:
$(resp.DATA[0]).each(function(key, value){
// your code
});
Loop in to your array like this using .each()
$.each(your_array, function(key, value) {
alert('Array Key is: '+ key + ' \n Array Key value is: ' + value);
});
.each() Iterate over a jQuery object, executing a function for
each matched element.

Find similar items in an object

I have an object that looks like so:
{
title: "test",
subtitle: "test",
"list-item-1": "This is item 1",
"list-item-2": "This is item 2",
"list-item-3": "This is item 3"
}
I want to find all keys in that object that end with a -1, or any -numerical value. And then group all of those together in some way that I can access them by calling something like "if an item has a -1 at the end of it, find all other items that have the same first part (list-item in this case) and save them to their own array or variable.
How would I go about this?
one simple way to harvest properties is to use built in methods like keys(), filter(), and test():
var obj={
title: "test",
subtitle: "test",
"list-item-1": "This is item 1",
"list-item-2": "This is item 2",
"list-item-3": "This is item 3",
};
var arrOK=Object.keys(obj).filter(/./.test, /list-item-\d+$/);
alert(arrOK); // shows: "list-item-1,list-item-2,list-item-3"
First of all, it isn't an array - that is a Javascript Object, however it is malformed in that there are not commas between items.
You can iterate through the object like so, and access the name of each object property as below.
for (item in obj) {
if (obj.hasOwnProperty(item)) {
// the 'item' variable is the name you are looking for.
// use a regex pattern to match on -#.
}
}
You can use for..in to iterate over the object keys and then just do some simple string/regex matching.
var new_obj = {};
// iterate over keys in object
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
// ends in "dash number"
if (key.match(/-\d+$/)) {
// get new key by stripping off "dash number"
var newkey = key.replace(/-\d+$/, "");
// ensure new object has this property; make it an array
if (!new_obj.hasOwnProperty(newkey)) {
new_obj[newkey] = [];
}
// append original object item to this new property
new_obj.push(obj[key]);
}
}
}

Categories