Js: How can i convert an Object property name to a string - javascript

I want to iterate through an object and get the property names so i can use them to retrieve a localstored item.
for (var property in parts) {
if (parts.hasOwnProperty(property)) {
var item = localStorage.getItem(property);
console.log(item);
}
}
how can i achieve this ?

You can get all object keys as array of strings via Object.keys(object), and then iterate through this array with any iteration method for arrays, for example, let's use forEach:
const obj = {
one: true,
two: 2,
three: 'Value three'
}
const keys = Object.keys(obj);
keys.forEach(key => {
console.log('Current key:', key);
//const item = localStorage.getItem(key);
})

Related

How to convert json object keys into different arrays removing the duplicate

I'm having the JSON like this i need to group this JSON with all the keys in JSON object and value should in array (excluding duplicates).
var people = [
{sex:"Male", name:"Jeff"},
{sex:"Female", name:"Megan"},
{sex:"Male", name:"Taylor"},
{sex:"Female", name:"Madison"}
];
My output should be like
{"sex":["Male","Female"],"name":["Jeff","Megan","Taylor","Madison"]}
how we can able to achieve this
function getValues(array) {
var result = {};
array.forEach(obj => {
Object.keys(obj).forEach(key => {
if(!Array.isArray(result[key]))
result[key] = [];
result[key].push(obj[key]);
})
})
return result;
}
You could use the Array.reduce() method to transform your array into a single object:
var people = [
{sex:"Male", name:"Jeff"},
{sex:"Female", name:"Megan"},
{sex:"Male", name:"Taylor"},
{sex:"Female", name:"Madison"}
];
const transformed = people.reduce((acc, e) => {
Object.keys(e).forEach((k) => {
if (!acc[k]) acc[k] = [];
if (!acc[k].includes(e[k])) acc[k].push(e[k]);
});
return acc;
}, {});
console.log(transformed);
If for one of the object keys (sex or name in this case) a value array does not exist, it is created. Before a value is pushed into any of the value arrays, it is verified that it is not already present in that array.

How to get the length of an object array object in angular

How to get the length of an object array object in angular.
Here's the code:
list.component.ts
const obj: any = {};
this.days.forEach((x: any) => {
const itemFilter = this.rowData.filter((item: any) => item);
itemFilter.forEach((item: any) => {
const date = format(item.lastpmdate, 'YYYY-MM-DD');
if (format(x.date, 'YYYY-MM-DD') === date) {
if (obj[date]) {
obj[date].push(item);
} else {
obj[date] = [item];
}
}
});
});
What I need is to get the length of the object array.
Thanks in advance.
You can list the keys of the target object with Object.keys and then check its length as a normal array:
Object.keys(this.days).length
If you have an object of arrays:
Object.values(this.days).map(v => v.length)
Object.values() allows to iterate over the object values instead of the keys.
Having these, you can then get the length for each of the inner arrays.

how to display both key and value in object using javascript?

I don't know if this is possible in javascript. I have a object that is dynamic.
like
const list = {eb: 'blue', et: 'green'}
anytime my list value will change like
const list = {er: 'yellow', ex: 'black'}
How can get the key value in my object? like I'm going to display both key and value for it.
const ikey = 'eb'
const ivalue = 'blue'
You can use Object.entries.
let list = {eb: 'blue', et: 'green'}
const keyValue = (input) => Object.entries(input).forEach(([key,value]) => {
console.log(key,value)
})
keyValue(list)
list = {er: 'yellow', ex: 'black'}
keyValue(list)
You can use for..in ,
for (var key in list) {
console.log(key, list[key]);
}
With ES6, you can use Object.entries
for (let [key, value] of Object.entries(list)) {
console.log(key, value);
}
try
for(var key in objects) {
var value = objects[key];
}
You can use the Object.keys(objectNameHere) method of the Object prototype to cycle through keys by name and enumeration.
Try this
const list = {er: 'yellow', ex: 'black'};
Object.keys(list).forEach(e=>console.log(e+"="+list[e]))
To avoid much computation and since V8 is great at handling JSON operations, you can simply JSON.stringify(obj) to give you all entries. Only problem is that you will have no control over how certain value types should be handled i.e. in that case, you will only remain with primitives as values.
Use Object.entries() to get a list of key/value pairs from your object. Then you can iterate over the pairs and display them with Array.forEach():
Object.entries({ a: 'hello', b: 3 }).forEach(([key, val]) => {
console.log(key, val);
});
You can get a list of keys with Object.keys() and a list of values with Object.values():
const obj = { a: 'hello', b: 3 };
console.log(Object.keys(obj));
console.log(Object.values(obj));
console.log(Object.entries(obj));
Lastly, you can iterate over the object keys directly with a for...in loop, in which case you have to use bracket notation to access the property on your object:
const obj = { a: 'hello', b: 3 };
for (const key in obj) {
console.log(key, obj[key]);
}
Try using the for..in operator
var obj = {
Name: 'Mohsin ',
Age: 20,
Address: 'Peshawar',
}
for (var keys in obj) {
console.log(keys, ':', obj[keys])
}

JavaScript or Lodash find objects by key

In an array of objects with diff keys, how do I find objects by key using ES6 or Lodash?
const arr = [{a:2}, {b:3}, {fred:10}]
I want the result to be:
=> [{a:2}, {fred:10}]
I don't want to use an omit style approach.
const filtered = arr.filter(obj => obj.hasOwnProperty("a") || obj.hasOwnProperty("fred"));
// or, if you have dynamic / lots of keys:
const keys = ["a", "fred"];
const filtered = arr.filter(obj => keys.some(key => obj.hasOwnProperty(key));
filter method will be useful. Create a function and pass an array of keys. Inside filter function check if the key is matching with the parameter array. If it passed then return that object
var orgObject = [{
a: 2
}, {
b: 3
}, {
fred: 10
}];
function searchByKey(keyNames) {
return orgObject.filter(function(item) {
for (var keys in item) {
if (keyNames.indexOf(keys) !== -1) {
return item
}
}
})
}
console.log(searchByKey(['a', 'fred']))
Basically you want all the objects from the array who have the fields a or fred. You can use the hasOwnProperty() on the objects while filtering.
_.filter(array, elem => elem.hasOwnProperty('a') || elem.hasOwnProperty('fred'));

How to get a number value within an object that is in an object

My code:
rbx.getPlayers(539310, 1).promise.then(players => {
console.log(players)
for (var list in players.players) {
console.log(list)
var key = Object.Key(list)
console.log(Key)
}
})
What it outputs:
{ total: 9,
players:
{ AgentJay400: 65910635,
MatthewHAndreas: 49787909,
coolguysocoolroblox: 165524669,
CAMPER5155: 45422370,
Mavnkei: 69082588,
kaankerem123: 92305180,
egehan432: 120777218,
panpanaber54: 31962303,
IXTactical_CactusXI: 17451343 } }
AgentJay400
MatthewHAndreas
coolguysocoolroblox
CAMPER5155
Mavnkei
kaankerem123
egehan432
panpanaber54
IXTactical_CactusXI
Problem:
I need the number values of each user (So {AgentJay4000: 65910635} I would want the 65910635) Node.js does not seem to have Object.keys so... I have no clue how to get the number...
Node should definitely have Object.keys. If your version doesn't you should update node. When you call Object.keys you get an array in return, so you can do awesome array things like map, reduce, forEach:
Object.keys(players.players).forEach(function(key) {
console.log(key, players.players[key])
})
If you just want the number values, then map it:
Object.keys(players.players).map(function(key) {
return players.players[key]
})
Now you have an array of the numbers only.
Try like this.You can access your object value using . operator.
Suppose you have an object:
var obj={
key1:value1,
key2:value2
}
Then access values like obj.key1 or obj['key1'].
to get all the values.Use Object.values(obj);
var obj = { total: 9,
players:
{ AgentJay400: 65910635,
MatthewHAndreas: 49787909,
coolguysocoolroblox: 165524669,
CAMPER5155: 45422370,
Mavnkei: 69082588,
kaankerem123: 92305180,
egehan432: 120777218,
panpanaber54: 31962303,
IXTactical_CactusXI: 17451343 } };
var players = obj.players;
var number_values = Object.values(players);
console.log(number_values );
You can output the keys and their associated numbers by doing the following:
rbx.getPlayers(539310, 1).promise.then(players => {
console.log(players)
for (var key in players.players) {
console.log(key, ':', players.players[key])
}
})
To demonstrate how Object.keys works an alternative method of accessing the players - this does the same as the above.
rbx.getPlayers(539310, 1).promise.then(players => {
var keys = Object.keys(players.players);
for (var i = 0; i < keys.length; i++) {
let key = keys[i];
let player = players.players[key];
console.log(key, ':', players.players[key])
}
});
The mistakes you made in your attempt were you were attempting to access Object.key which was a typo for Object.keys and attempting to obtain a list of keys from a string (as a loop such as for(var key in obj) will set key to each key in obj and all object keys are strings).

Categories

Resources