How to get the name from the array in javascript? - javascript

I am fairly new to JavaScript and I am trying to extract the name Sam from the array. The output that I'm getting is name. How do I get Sam? Thank you in advance. I apologize but I know this is a fairly novice question.
I am trying to loop by using forEach.
let Person = {
name: ['Sam']
}
let handler = Object.keys(Person)
handler.forEach(function(element){
console.log(element)
})

Object.keys() only gives you keys
Use Object.entries() if you want key and value
Use Object.values() if you only want values
let Person = {
name: ['Sam']
}
for (const fn of ["values", "keys", "entries"]) {
console.log(`Using: Object.${fn}()`);
for (const v of Object[fn](Person)) {
console.log(v);
}
}

Instead of Object.keys use Object.values

If you know in advance that your name array is located under the key name, then access it directly
const person = { name: ['Sam'] };
console.log(person.name);
console.log(person.name[0]);
Otherwise, use Object.values() to enumerate the values in the object, but you might get more values than simply the names array and you will have to find out which value contains the names you are looking for:
const person = { name: ['Sam'], anotherProp: 'hello' };
console.log(Object.values(person));
Using Object.entries() is not helpful in this situation as if you use it, it means that you know under which property is located your name array, and if this is the case, simply access the array directly.

let Person = {
name: ['Sam',"Bob","Alice"]
}
let count = Person.name.length;
for(let i = 0; i<count; i++){
console.log( Person.name[i])
}

If you use Object.keys() you can get the value by using object[key] bracket notation or object.key dot notation.
Object.keys(obj).forEach(key => obj[key]);
let Person = {
name: ['Sam']
}
Object.keys(Person).forEach(name => console.log(`${name} = ${Person[name]}`));

Related

In nodeja/nodered, how do i address this property?

I want to use this property in my function node. How do i address this property? msg.payload.tagData.???
You will need to use the square bracket notation:
msg.payload.tagData['0828CA741AEEB01700172093000004E3'].inIntensity
msg.payload.tagdata['0828CA741AEEB01700172093000004E3']
if its dyanmic and you only need to access the first property, you can do
msg.payload.tagData[0]
if you want to dynamically get all of the data of those properties, you can loop through them
I was looking for the keys operator. This worked for me:
payload=msg.payload;
for(let key in payload.tagData) {
payload.tagData[key].epc = key;
}
return msg;
Those are hexadecimal attributes, you might need to convert them to decimal before you can access them
const hexes = [
'44c7b3b30db9c13b5',
'68b739c1c6ca2bf7a',
'f8fde53b68ee6b9eb',
'7f61b32d42b4bed47',
'f463cb64441e85a81',
]
let obj = {}
hexes.map((hex, i) => obj[`0x${hex.toUpperCase()}`] = i)
console.log(obj)

How to replace array of object property name in javascript

I need to replace array of object in javascript. Here is my data variable and I want to update data variable
const data = [{name: "poran", id: "22"}];
Expected value:
data = [{value: "poran", age: "22"}];
How can I replace array of object?
You can create a new array with the use of .map() and some Object Destructuring:
const data = [{name:"poran",id:"22"}];
const result = data.map(({ name:value , id:age }) => ({value, age}));
console.log(result);
You can use a .forEach() loop over the array:
data.forEach((obj) {
obj.value = obj.name;
obj.age = obj.id;
delete obj.name;
delete obj.id;
});
It's a little simpler if you just make a new array with .map(), but if you need to keep the old objects because there are lots of other properties, this would probably be a little less messy.
try this:
const data = [{name:"poran",id:"22"}]
const rst = data.map(res=>({value: res.name, age: res.id}));
console.log(rst)

Check if object contains array

Is there a way to check if my object contain array? for example:
let object1 = {
name:'abc',
items:[
{item_name:'123'},
{item_name:'456'}
]
}
Imagine object1 is coming from server and I am not sure that it will or will not (or even have more) array in it. Is there a proper way to do this?
You can use Array.prototype.some and Object.values() to iterate and determine if any value is an array.
let object1 = {
name:'abc',
items:[{item_name:'123'},{item_name:'456'}]
}
let res = Object.values(object1).some((val) => Array.isArray(val));
console.log(res);
You can use Object.keys()
The Object.keys() method returns an array of a given object's own property names, in the same order as we get with a normal loop.
and Array.prototype.some()
The some() method tests whether at least one element in the array passes the test implemented by the provided function.
with Array.isArray()
The Array.isArray() method determines whether the passed value is an Array.
let object1 = {
name:'abc',
items:[
{item_name:'123'},
{item_name:'456'}
]
}
var r = Object.keys(object1).some(i => Array.isArray(object1[i]));
console.log(r);
You can use Some and Array.isArray
let object1 = {name:'abc',items:[{item_name:'123'},{item_name:'456'}]}
let op = Object.values(object1).some(e=>Array.isArray(e))
console.log(op)
Use isArray(). It tells if an object is an array or not. Refer
let object1 = {
name:'abc',
items:[
{item_name:'123'},
{item_name:'456'}
]
}
Object.values(object1).forEach((e)=>{
if(Array.isArray(e))
{
console.log('true')
}})
Use find and isArray on Object.values, then convert length to Boolean:
let object1 = {
name:'abc',
items:[
{item_name:'123'},
{item_name:'456'}
]
}
console.log(Boolean(Object.values(object1).find(e => Array.isArray(e)).length));

ESLint doesn't allow for in

I have an object
currentValues= {hey:1212, git:1212, nmo:12121}
and I use for in like this:
for (const key in currentValues) {
if (Object.prototype.hasOwnProperty.call(currentValues, key)) {
yield put(setCurrentValue(key, currentValues[key]));
}
}
ESLint shows me an error which is saying:
ESLint: for..in loops iterate over the entire prototype chain, which is virtually never what you want. Use Object.{keys,values,entries}, and iterate over the resulting array. (no-restricted-syntax
How should I edit my code?
It says,
Use Object.{keys,values,entries}, and iterate over the resulting
array.
So you could do something like this to get the object keys as an array and then loop through the keys to make necessary changes.
currentValues= {hey:1212, git:1212, nmo:12121}
Object.keys(currentValues).forEach(function(key) {
yield put(setCurrentValue(key, currentValues[key]));
})
I used the following:
const keys = Object.keys(currentValues);
const values = Object.values(currentValues);
for (let i = 0; i < keys.length; i += 1) {
yield put(setCurrentValue(keys[i], values[i]));
}
This is correct and without ESLint errors.
You can get the array of all your values inside your object just doing
var myValuesInArray = Object.values(currentValues);
I would do it by refactoring, in the following ways.
const currentValues = { hey: 1212, git: 1212, nmo: 12121 };
Object.keys(currentValues).forEach((e) => console.log(`${e} : ${currentValues[e]}`));
Results:
hey : 1212
git : 1212
nmo : 12121
Object.values(currentValues).forEach((e) => console.log(`Values: ${e}`));
Results:
(2)Values: 1212
Values: 12121
Object.entries(currentValues).forEach((e) => console.log(`${e[0]} : ${e[1]}`));
Results:
hey : 1212
git : 1212
nmo : 12121
let animal = {
eats: "Eating",
};
let rabbit = {
jumps: "Jumping",
};
rabbit.__proto__ = animal;
for (const rabbitProps in rabbit) {
// This will print both eats and jumps properties because they're part of
// prototype chain
console.log("rabbitProps: ", rabbitProps);
}
// This prints only jumps as Object.keys shows only the keys of object
console.log(Object.keys(rabbit));
Checking out the above code you can see that when using for...in loop[ it will show all the properties that are part of object as well as properties set in the prototype chain of the object and so eslint suggests to use Object.keys or value or entries, as they do not look into prototype chain instead they just look at your object.
I know it is similar to the above, but here is a full example:
const data = res.data;
const keys = Object.keys(data);
const values = Object.values(data);
for (let i = 0; i <= keys.length; i += 1) {
if (Object.prototype.hasOwnProperty.call(values, i)) {
this.rows.push({
name: values[i].name,
email: values[i].email,
address: values[i].address,
phone: values[i].phone,
role: values[i].role,
});
}
}
try this instead:
Object.keys(currentValues).map(key => (yield put(setCurrentValue(key, currentValues[key]))));
Using for...in will iterate over all properties including those from Object prototype. I am not sure why you are doing Object.prototype.hasOwnProperty.call(currentValues, key)
instead of just:
currentValues.hasOwnProperty(key).
I think this should make ESLint aware that you are filtering for own properties only.
However, I suggest using for (const key of Object.keys()), which is more semantic.

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

Categories