Get object values without using Object.values() - javascript

I just started learning to code and am working on this challenge. Having issues finding any relevant guidance online. Thanks in advance.
function keys(json) {
var obj = JSON.parse(json);
let result = [];
for (const key in obj) {
result.push(key);
}
return result;
}
I got this to work for returning keys without using Object.keys and I sort of assumed I could just swap the 'key' for 'value' but that didn't work.
function keys(json) {
var obj = JSON.parse(json);
var values = Object.keys(obj).map((key,value)=>{ values.push(value) });
return values;
}
Also tried this, but I don't really understand the map function yet.

Is this what you are looking for?
const obj = {a:3, b:4}
const result = []
for (const key in obj) {
result.push(obj[key])
}
console.log(result)

With Object.keys you get an array of keys (own, enummerable) of the array. for mapping values, you need to take a property accessor with object and key.
function values(json) {
const object = JSON.parse(json);
return Object
.keys(object)
.map(key => object[key]);
}
console.log(values('{"foo":"bar","baz":42}'));

Related

Javascript: Map iterate object keys and values

Trying to get both key and value using the following script
jsonData = {"jurisdiction":"SCPB - LON","firstName":"David Dynamic"}
var keys = Object.keys(jsonData).map(function(keys, values) {
logInfo(jsonData[keys], jsonData[values]);
});
returns just the values:
2022-08-30 18:29:49 David Dynamic undefined
2022-08-30 18:29:49 SCPB - LON undefined
How can I get both? the js engine is spiderMonkey 1.8
Object.keys(jsonData).forEach(function(key) {
logInfo(key, jsonData[key]);
});
Object.keys documentation
Or as suggested by Kondrak Linkowski:
Object.entries(jsonData).forEach(([key, value]) => logInfo(key, value))
You likely want to use Object.entries to get the keys and values of the object.
If you want to do it with Object.keys, as in your example, you can modify it like this: (logging the key, and the value at this key)
const jsonData = {
foo: 'bar',
fizz: 'fuzz',
}
const logInfo = console.log
var keys = Object.keys(jsonData).map(function(key) {
logInfo(key, jsonData[key]);
});

reactJS adding a object array to and object within an object array

I got a response from a REST call, which returns and array with objects
response.data.steps
For example it looks like this
Now I need to add to each Child of this array an new Object Array.
What could be a smart solution for this problem?
Thanks.
In order to add a new array property to each item, you can simply do:
const steps = response.data.steps.map(step => ({
...step,
newObjectArray: [],
}))
you can usee Array.prototype.map() to do so
let result = response.data.steps.map(element => {
let ret = [element];
return ret;
});
let arr = [{a:1}, {a:2}, {a:3}];
arr = arr.map(element => {
let ret = [element];
return ret;
});
console.log(arr);

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

Convert Object to 2D array in JavaScript

Can we convert an Object to a 2D Array,
My Object is like this
So That Array Key will be like 'STARS_2' and value is ["STARS_4", "STARS_0", "STARS_12"]
with My attempts I can get something like this,
With this Code,
var testArray =[];
_.map(childFieldNames, function (value, key) {
var newArray = new Array();
newArray[key] = value;
testArray.push(newArray);
});
Here Keys are actually another array, which I do not want. I want key should be like 'STARS_2' , i.e. property of master object.
Is this what you need?
var ary2D = Object.keys(childFieldNames).map(function (key) {
return childFieldNames[key];
});
better version for what Shilly showed would be:
const arr2D = Object.values(childFieldNames);
Object.entries(obj)
E.g.
const objVariable = {name: "Ted", job: "Dentist"}
const 2dArray = Object.entries(objVariable)
console.log(2dArray) // will print [["name", "Ted"], ["job", "Dentist"]]
Object.entries is a static method that belongs to the Object class. As a parameter, it accepts an object and returns a two-dimensional array.
Read more about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
You don’t need to create your structure into 2D array to just iterate over each key and its respective value(which is an array). If you want to iterate over it you can do something like this.
const object = {
a: [1,2,3],
b: [2,3,5]
};
for (const [key, value] of Object.entries(object)) {
value.forEach(v=>{
console.log(`${key}: ${v}`);
})
}

Convert object literal notation to array

I used a literal as a dictionary, but a third party binding tool only takes arrays.
This is one way, is there a better one?
var arr = [];
$.each(objectLiteral, function () { arr.push(this); });
I think there is nothing wrong with your solution.
This is a shorter one:
var arr = $.map(objectLiteral, function (value) { return value; });
Your method is fine, clear and readable. To do it without jQuery, use the for (..in..) syntax:
var arr = [];
for (prop in objectLiteral) {
arr.push(objectLiteral[prop]);
}
In vanilla JS...
If we want to convert an object literal
var obj = {
species: 'canine',
name: 'Charlie',
age: 4
}
into an array of arrays
[['species', 'canine'], ['name', 'Charlie'], ['age', 4]]
here is one way
function objToArr(obj){
var arr = [];
for (var key in obj){
arr.push([key, obj[key]]);
}
return arr;
}
const objectLiteral = { hell: 'devil' };
const ver1 = Object.keys(objectLiteral); // ['hell']
const ver2 = Object.values(objectLiteral); // ['devil']
const ver3 = Object.entries(objectLiteral); // [['hell', 'devil']]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/keys
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/entries
In ES2017 you can now use Object.entries and with ES6 destructuring support you can use the resulting array pretty nice, example
Object.entries(objectLiteral).filter(([key, value]) => !!value).map(([key, value]) => key)
Gets you all properties with a value

Categories

Resources