Read a value from JSON Array without entity - javascript

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'

Related

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))

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

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']

Can't create JS object with array indices as key & value?

Task: convert an array into an object with one key-value pair, where the first array item is the key, and the last array item is the value.
E.g., [1,2,3] should convert to {1: 3}
I can't get it to work as:
function transformFirstAndLast(array) {
var firstLast = {
array[0]: array[-1]
};
return firstLast
}
But only as:
function transformFirstAndLast(array) {
var firstLast = {};
firstLast[array[0]] = array[array.length - 1];
return firstLast
}
...why doesn't the first work? Why can't you index the array for the key & value?
You could pop the last element and take a computed property for the object. (For the first element, you could take Array#shift, if you like to do it in the same manner.)
function transformFirstAndLast(array) {
return { [array[0]]: array.pop() };
}
console.log(transformFirstAndLast([1, 2, 3]));
ES5 with a temporary variable.
function transformFirstAndLast(array) {
var temp = {};
temp[array[0]] = array.pop();
return temp;
}
console.log(transformFirstAndLast([1, 2, 3]));
Take the first is easy, take the last is the size minus one like this:
function firstAndLast(array) {
var ary = {};
ary[array[0]] = array[array.length - 1];
return ary;
}
console.log(firstAndLast([1,2,3]))
First, you must remember than an array is a type of JavaScript object and, in JavaScript, an object property (a.k.a. "key") can be accessed or assigned in two ways:
via "dot notation"
object.property = value;
via array syntax
object["property"] = value;
Next, remember that, in JavaScript, if you assign a value to a property that doesn't exist (using either syntax from above), the property will be created, like in the following:
console.log(window.someNewProperty); // undefined
window.someNewProperty = 17; // This causes the property to be created
window["someOtherNewProperty"] = "Voilla!"; // So does this, just with array syntax
console.log(window.someNewProperty); // 17
console.log(window["someOtherNewProperty"]); // "Voilla!"
Now, moving on to the specifics of an array, it's critical to understand the difference between an object property/key name (which is always represented as a string) and an array index (which is always a non-negative integer up to the max integer in JavaScript). So, if you have an array and seemingly assign a value to a negative index, you are actually creating a property that is named the negative index and not actually adding to the length of the array or making a new indexed position in the array. We can see that here:
var myArray = ["a", "b", "c"];
myArray[-1] = 15;
console.log(myArray.length); // 3 not 4
console.log(myArray[-1]); // 15
// Now to prove that -1 is a string name for a new property and not an index:
console.log(myArray); // Notice no 15 in the indexed values?
// And, if we enumerate the object (not just the indexes), we'll see that we actually created
// a property with [-1], not a new index.
for(var prop in myArray){
// Note that prop is not the value of the property, it's the property name itself
console.log(typeof prop, prop, myArray[prop]);
}
So, to sum up, Arrays have non-negative integer indexes to store the items that make up the length of the array, but Arrays are also objects and have properties, like all other objects do. Any bracket assignments that use anything other than non-negative integers as the key name will become new properties, not array indices.

Get the value of an object with an unknown single key in JS

How can I get the value of an object with an unknown single key?
Example:
var obj = {dbm: -45}
I want to get the -45 value without knowing its key.
I know that I can loop over the object keys (which is always one).
for (var key in objects) {
var value = objects[key];
}
But I would like to know if there is a cleaner solution for this?
Object.keys might be a solution:
Object.keys({ dbm: -45}); // ["dbm"]
The differences between for-in and Object.keys is that Object.keys returns all own key names and for-in can be used to iterate over all own and inherited key names of an object.
As James Brierley commented below you can assign an unknown property of an object in this fashion:
var obj = { dbm:-45 };
var unkownKey = Object.keys(obj)[0];
obj[unkownKey] = 52;
But you have to keep in mind that assigning a property that Object.keys returns key name in some order of might be error-prone.
There's a new option now: Object.values. So if you know the object will have just one property:
const array = Object.values(obj)[0];
Live Example:
const json = '{"EXAMPLE": [ "example1","example2","example3","example4" ]}';
const obj = JSON.parse(json);
const array = Object.values(obj)[0];
console.log(array);
If you need to know the name of the property as well, there's Object.entries and destructuring:
const [name, array] = Object.entries(obj)[0];
Live Example:
const json = '{"EXAMPLE": [ "example1","example2","example3","example4" ]}';
const obj = JSON.parse(json);
const [name, array] = Object.entries(obj)[0];
console.log(name);
console.log(array);

Explanation for in loop javascript

I'm having trouble understanding the way this for in loop works.
function createSimpleNode(name, options, text) {
var node = document.createElement(name);
for (var o in options) {
node.setAttribute(o, options[o]);
}
if (text) {
node.innerHTML = text;
}
return node;
}
The For in loop gives a way to iterate over an object or array with each value and key.
It can be applied over an object or Array.
For an Object
For an object it gives each key in the object as the ITER variable. Using this variable you can get the corresponding value from object.
var options = {a:1,b:2};
for (var key in options) {
console.log(o,options[key]);
}
Will Iterate over the options object and print each key and it's value.
a 1 //first key is a and options["a"] is 1
b 2 //first key is a and options["b"] is 2
For an Array
For an array it gives each index in the array as the ITER variable. Using this variable you can get the corresponding element from array.
var options = ["a","b"];
for (var index in options) {
console.log(index,options[index]);
}
Will Iterate over the options array and print each index and element on given index. Output will be:-
0 a //first index is a and options[0] is a
1 b //second index is a and options[1] is b
This is a for..in loop. it iterates over the properties of an object (options, in this case), and allows you access the said property in each iteration using the [] operator.
In your example, you iterate over options properties, and set them all as attributes of node.

Categories