Lodash to check object property on array elements - javascript

I want to use lodash to find a property of an object at a specific array element.
Lets say I am hitting an api and getting response which sets it to the react state "personsDetails" (whose initial value was null), so now it becomes
let personsDetails=[{name:'king',id:2},{name:'queen',id:3}] //sometimes i get 1 object and sometimes 2
now when i want to access "name" property of 2nd object i do
personsDetails && personsDetails[1] && personsDetails[1].name
So is there any shorted syntax of accessing it via using lodash ? If the values doesnt exist i need null
As far as i know _get property works with object only so here i am dealing with array and then object

You can still use get and set the default as null
let personsDetails=[{name:'king',id:2},{name:'queen',id:3}]
let res = _.get(personsDetails, '1.name',null) //or _.get(personsDetails, '[1].name',null)
console.log(res)
console.log(_.get(undefined, '1.name',null))
console.log(_.get([], '1.name',null))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
or can use nth along with get and set the default as null
let personsDetails=[{name:'king',id:2},{name:'queen',id:3}]
let res = _.get(_.nth(personsDetails,1),'name',null)
console.log(res)
console.log(_.get(_.nth([],1),'name',null))
console.log(_.get(_.nth(undefined,1),'name',null))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

Related

Gets undefined when trying to access a null value inside a nested object in vue js

I have an object
const data={a:'value1',b:{c:'null'}}
Now when I try to access 'c', I get 'undefined' but I am getting 'b'.
I tried accessing like this:
console.log(data.b) returns {c:'null'} but
console.log(data.b.c) returns undefined
Use this
let {c} = data.b;
console.log(c);
It will resolve your problem.
Update:
In vue components, sometimes you are not able to fetch nested object like this
data.b.c
so you have to use this strategy to access nested object attribute. like this
let {c} = data.b

how extract an object from an array where all of the keys are the same

I have been stuck on this for a while. I have an array of object where the key is the same for all of the objects (see below). I am trying to extract the data from the first object in the array [0]. However when I console.log the data I get 'Cannot read property '0' of undefined. Here is the image of the data that I receive when I just filter the data.
And here is the code that I am using to get that data:
const handleClick = e => {
e.preventDefault();
const buttonValue = e.target.value;
console.log(buttonValue);
grid.on('rowClick', (...args) =>
args.filter(data => {
data.cells;
console.log(data.cells);
})
);
};
when I add an index of 0 to the console.log console.log(data.cells[0]); I get the cannot read property 0 of undefined
I am not sure where data.cells is coming from. Property 0 of undefined clearly tells you that there is no such property as cells on data.
Also, I am not sure what exactly you mean by extracting objects, but I will be assuming that you need programmatic access to the objects.
First off, if you can see that the statement (8)[ n, n, n, n, n, n, n, n ] tells you that it is an object with 8 objects of type n.
Here is something I simulated in a console. So you can clear that up.
And to access it you need to use array indexing. Let's assume the name of the array is data -
const firstElement = data[0]
You can also use loops and higher-order functions such as map(), forEach() too.

how to access js object properties?

I'm lost on how to get object properties in JS. I'm getting values from firebase and I wanted to filter the result by its id:
//id is from query params (selecting 1 item from view)
const snippet = snippets.filter(snips => {
if(snips.id == id) return snips;
})
If I console.log after these lines, I'm getting this:
const obj = snippet[0];
So I tried to get properties by using snippet[0] which returns this:
But if I try to get properties such as:
console.log(obj['id']);
//console.log(obj.title); - tried this as well
it returns:
Entering data:
This isn't how the array::filter function works. It iterates over the array and the callback returns a boolean true/false if the element should be returned in the result array.
const snippet = snippets.filter(snips => snips.id == id)
Issue
Cannot read property "title" of undefined
This is saying that snippet[0] is currently undefined when trying to access any properties
snippet[0].title, a root title property also doesn't exist in your other console log
Solution
Your snippet is (possibly) an array of 1 (or 0) element, so in order to access the title nested in data property
snippet[0].data.title
And in the case that the array is empty or has an element without a data property, use optional chaining or guard clauses to check the access
snippet[0]?.data?.title
or
snippet[0] && snippet[0].data && snippet[0].data.title
looking at what you are asking you need to enter first the data.
console.log(obj[0].data.content)

Javascript get value from an object inside an array

I have an object with key value pairs inside an array:
var data = [
{
"errorCode":100,
"message":{},
"name":"InternetGatewayDevice.LANDevice.1.Hosts.HostNumberOfEntries",
"value":"2"
}
];
I want to get the value of "value" key in the object. ie, the output should be "2".
I tried this:
console.log(data[value]);
console.log(data.value);
Both logging "undefined". I saw similar questions in SO itself. But, I couldn't figure out a solution for my problem.
You can use the map property of the array. Never try to get the value by hardcoding the index value, as mentioned in the above answers, Which might get you in trouble. For your case the below code will works.
data.map(x => x.value)
You are trying to get the value from the first element of the array. ie, data[0]. This will work:
console.log(data[0].value);
If you have multiple elements in the array, use JavaScript map function or some other function like forEach to iterate through the arrays.
data.map(x => console.log(x.value));
data.forEach(x => console.log(x.value));
data is Array you need get first element in Array and then get Value property from Object,
var data = [{
"ErrorCode":100,
"Message":{},
"Name":"InternetGatewayDevice.LANDevice.1.Hosts.HostNumberOfEntries",
"Value":"2"
}];
console.log(data[0].Value);
Try this...
Actually Here Data is an array of object so you first need to access that object and then you can access Value of that object.
var data = [
{
"ErrorCode":100,
"Message":{},
"Name":"InternetGatewayDevice.LANDevice.1.Hosts.HostNumberOfEntries",
"Value":"2"
}
];
alert(data[0].Value);
what you are trying to read is an object which an element of an array, so you should first fetch the element of array by specifying its index like
data[0] and then read a property of the fetched object, i.e. .value,
so the complete syntax would be data[0].value
Hope it helps !

Get object property value

I have an object that contains an array of objects from which I need to get a value of their properties.
As an example this is what I need to get:
Stronghold.bins.models[0].attributes.entity.title
Which returns "Stronghold Title 1"
function grabItemName(){
var itemName=$(Stronghold.bins).each(function(){
return this.models[0].attributes.entity.title == title;
console.log(itemName);
})
};
(if there is a better way for me to ask this question please let me know)
I apologize if this was poorly asked!
The current issue is that it does not understand the array value '[0]' and cannot read it as it is undefined. What do I need to do to grab the 'title' value of all items in the array?
What do I need to do to grab the 'title' value of all items in the array?
That's what .map [docs] is for. It lets you map each value in an array to another value.
In the following I assume you want to iterate over each Stronghold.bins.models, because iterating over Stronghold.bins does not make sense with the provided information:
var titles = $.map(Stronghold.bins.models, function(obj) {
return obj.attributes.entity.title;
});
// `titles` is now an array containing `.attributes.entity.title;` of
// each object.
The current issue is that it does not understand the array value '[0]' and cannot read it as it is undefined.
Well, that won't happend anymore ;) In your example you where iterating over the properties of the Stronghold.bins object. One of these properties is models itself (!) and I doubt that any other property value has a models property.
Try using the other version of the each function:
$.each(Stronghold.bins, function () {
});
The version you are using is for looping through an element on the page, e.g $('body div p').each(function() {}), which isn't what you want in this instance: You want to loop over the values contained in Stronghold.bins.

Categories