How to print property name rather than the whole JS object? - javascript

Let's suppose :
this.state.keys[index] =
Object { -ID01: Object, -ID02: Object, -ID03: Object, -IDO4: Object }
How to print-ID02 for example ? I am looking for the propriety name-ID02 not what's inside and its actual values
// Expected Output -ID02 (string)

Object.keys(this.state.keys[index])
will give you the keys in that object as an array.
More info here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

you could Object.keys() and index into the key of interest. For e.g. -ID02 would be at index 1. Therefore, Object.keys(this.state.keys)[1] would give you what you are looking for.

If you have an object obj, then Object.keys(obj) will return an array of all the keys in that object. For eg:
const obj = { '-ID01': Object, '-ID02': Object, '-ID03': Object, '-IDO4': Object };
let keys = Object.keys(obj); //['-ID01', '-ID02', '-ID03', '-ID04']

Related

JS - Transform an Object into an Array unless it is an array

Let's say we have to iterate over either an Object or an Array of Objects. I want to transform the Object into an array of one object and then iterate in my React App, to present what I want.
Let' take an example:
// Returned value as object
const zoo = {
lion: '🦁',
panda: '🐼',
};
// I want to transform it into Array of 1 Object
const zoo = [{
lion: '🦁',
panda: '🐼',
}];
How could I achieve that, but only if the returned value is not already an array?
Just check if it is an array. If not, convert it:
return Array.isArray(zoo) ? zoo : [zoo];
function handleObj(obj){
return Array.isArray(obj)?obj:[obj]
}
console.log(handleObj({label:'aa',value:1}))

Read a value from JSON Array without entity

I need to access the 2.2.10.60 and "bank overdrafts...." value from the following array --
May I ask about how to get it?
Here with my code.
var json=chunk.toString();
var obj = JSON.parse(json);
session.send(obj.clauses[0]);
console.log(obj.clauses[0]);
But I can't get the value of "2.3.10.60" and "Bank overdrafts....".
and the inside the "clauses" array will always change.
I had Solved by my own:
var graph = JSON.parse(json);
for(var i=0;i<graph.clauses.length;i++){
var obj=graph.clauses[i];
console.log(obj);
var clause_id;
var clause_text;
for(var key in obj)
{
clause_id=key;
clause_text=obj[key].toString();
session.send(clause_id+"<br>"+clause_text);
}
}
You could use Array#find and check if the wanted property exist in the object. Then take the object and use an property accessor for the result.
key = '2.2.10.60'
result = clauses.find(object => key in object)[key];
If you are not sure about if the array does not contain any object with this key, take an default object or check in advance if find returns a truthy value (like an object), take this
var key = '2.2.10.60'
result,
temp = clauses.find(object => key in object);
if (temp) {
result = temp[key];
}
For a dynamic approach, you could take a variable for the wanted key.
For getting just the first entry of the object, you could take the entries of index zero. This approach assumes, theat only one key/value pair exists in the object.
var [key, value] = Object.entries(object.clauses[0])[0];
// ^^^^^^^^^^^^ target by destructuring an array
// ^^^^^^ source
// ^^^^^^^ property
// ^^^ index/the first one
// ^^^^^^^^^^^^^^ ^ get all key/value pairs of object
// ^^^ take the first pair only
You can use the Array.find() method and verify if the object keys have the value you need.
clauses.find(object => Object.keys(object).includes('2.2.10.60'))
This will return an array of the first object whose keys include '2.2.10.60'

How to keep the order of JSON numeric keys in nodejs

var json = `{"3":0,"2":0,"1":0}`
var obj = JSON.parse(json)
console.log(JSON.stringify(obj))
console.log(json === JSON.stringify(obj))
output
{"1":0,"2":0,"3":0}
false
I expect to get it
{"3":0,"2":0,"1":0}
true
How to do
This is because json is an object after parsing and object's keys are not guaranteed to be in order
You can use map & it guarantees the order of the keys
That's not possible. In ES6, the keys are traversed in the following order:
First, the keys that are integer indices, in ascending numeric order.
Then, all other string keys, in the order in which they were added to the object.
Lastly, all symbol keys, in the order in which they were added to the object.
The integer keys are sorted in ascending order irrespective of the order in which they are inserted
var a = {};
a[3] = "three"
a[2] = "two"
a[1] = "one"
console.log(JSON.stringify(a))
Reference
You might also want to read: Does JavaScript Guarantee Object Property Order?
You can use array of objects with guid property
const text = '[{"id":3,"value":0},{"id":2,"value":0},{"id":1,"value":0}]'
const json = JSON.parse(text)
console.log(JSON.stringify(json))
You could spend the keys a dot and by iteratong these keys are in the original insertation order, but not accessable with just the number. This needs a dot as well.
var json = `{"3.":0,"2.":0,"1.":0}`
var obj = JSON.parse(json)
console.log(obj[2])
console.log(JSON.stringify(obj))
console.log(json === JSON.stringify(obj))

cant seem to loop through object keys

I have an object through which im trying to loop through using for..in. But it gives me "0" as values instead of the object keys such as piidata, location, risklevel etc.
var srcObj = [{
location: "34",
piidata: "sdafa",
risklevel: "Medium"
}]
for (var prop in srcObj) {
console.log(prop);
}
srcObj is an array, as evidenced by the []. Inside it is an object at index 0.
Your "srcObj" is an array. This is indicated by the wrapping [ ... ]. If you console.log srcObj[0], you should get the object itself.
while you are looping the javascript object it's return the index/key of object
so if you are trying to get value of each key try.
for( var prop in srcObj )
{
console.log(srcObj[prop]);
}
if you are trying to get each key name then try this one
for( var prop in srcObj )
{
console.log(prop);
}
All you need to do
for (var prop in srcObj) {
console.log(srcObj[prop]);
console.log(srcObj[prop]["risklevel"]); // --> Medium
var keyNames = Object.keys(srcObj[prop]); // --> return keyNames as array
console.log(keyNames[0], keyNames[1]); // --> location piidata
}
Your srcObj is an array. You can tell by the square brackets [] it's enclosed in. But Chrome says Object. Right. Javascript types are a little strange. Check out this page.
If you want to access the key/values in the object, you can specify the index of the object within the array. srcObj[0] in this case. If you want to get the object out of the array and deal with it just as an object, you can do something like this:
var trueObject = srcObj.shift()
Which removes and returns the first element of an array and assigns it to your variable.
Your srcObj is actually an array (identified by the [ and ] literals) which contains an object as its only element.
To access the parameters of the single object inside the array, use the following syntax:
for( var prop in srcObj[0] )
{
console.log(prop);
}
jsFiddle Demo

array.filter is undefined when looping over objects

I have an array of objects where the value i'm trying to find is a number, i'm wanting to return the underlying objects array when the correct number is found, and the value i'm passing to search is type number.
I keep getting "array.filter is undefined" error. I'm assuming it's because the structure is one object and not an array? Whats the best way to do this?
I have a fiddle here
var obj = array.filter(function ( obj ) {
return obj === 2000;
})[0];
console.log( obj );
Your "array" is not an array - its an object
var array = {
"legend": {
....
}
}
What you want instead is just read properties of an object - some of them are numeric, which means you'll need the square bracket notation:
var obj = array.legend["2000"];
Updated fiddle: http://jsfiddle.net/gJPHw/221/

Categories