how to get values of specific key in javascript - javascript

I have this Object
const fruits = {
apple: 28,
orange: 17,
pear: 54,
};
I want to insert the values from the key "apple" into an empty array
with Object.values.fruits I get all the values, so I tried it with Object.values(fruits.apple) to specify the key
const leere_liste = [];
const values = Object.values(fruits);
leere_liste.push(values);
but this gives my an empty array, is there a method for that which I'm unaware of ?

Couple of things.
Its Object.values(fruits), not Object.values.fruits.
Object.values only works on objects. So while it will work on fruits, it won't work on a specific property of fruits unless that property contains an object too.
Works:
const fruits = {apple: 28, orange: 17, pear: {a: 54, b: 22}};
console.log(Object.values(fruits.pear));
// [54, 22]
Also, since you're getting an array back from Object.values, if you push that onto another array you'll just have an array containing an array of those values.
If you want a single dimensional array, simply assign it like:
const leere_liste = Object.values(fruits);

Not sure what " I get all the values, so I tried it with Object.values(fruits.apple) to specify the key" means, as in your code you are simply getting the values of the entire array, not just apple, and also the property apple itself doesn't have "values", it has only one value.
Object.values is a function that takes an object as a parameter and returns an array of all of the values of the object only, usually in alphabetical order of the keys, but the actual final product has no connection to the original keys or the object, just given it itself it would be impossible to determine what values correspond to what keys
Hence it's a bit difficult to understand what you are trying to do, if you are trying to only insert the value of "apples" into an empty array, I don't know why you can't just do emptyArray.push(fruits.apple), if you are trying to make a method for pushing the value of any given fruit to an array, you can simply use bracket notation on a function const fruity= (arr, obj, key) => arr.push(obj[key]) then to use it with your variables fruity(leere_liste, fruits, "apple")
If you want to convert the keys AND values into a new kind of array that you can work with, then what you need is Object.entries, it is a function that takes an object as a parameter and returns a two dimensional array, with the first element of each sub array representing the key of the respective object property, and the second element of each sub array representing the corresponding value to said key of the original object.
To use it just call var newArray=Object.entries(fruits), in general this is helpful if you want to modify objects using expressions, such as Array.map, Array.forEach etc, although I'm not sure if you need it to simply add a property of an object to an array, to do that, see paragraphs above

Related

After trying this example, feeling confused on the basics of Maps and Set in Javascript

I am trying to apply some examples to better understand the difference of Map and Set and the behaviour of each one seems confusing. Look at the examples and output below
Map example:
let nameMap = new Map([
['name', 'stack'],
['name', 'overflow'],
['domain', 'technology']
]);
// iterate over keys (nameMap)
for (let name of nameMap) {
console.log(JSON.stringify(name));
}
output:
["name","overflow"]
["domain","technology"]
Set Example:
let nameSet = new Set([
['name', 'stack'],
['name', 'overflow'],
['domain', 'technology']
]);
// iterate over keys (nameSet)
for (let name of nameSet) {
console.log(JSON.stringify(name));
}
output:
["name","stack"]
["name","overflow"]
["domain","technology"]
My question is why map returns only the second occurence of two similar objects?
Set returns all three objects even though first two keys and values being same, while it supposed to delete one of them.
My question is why map returns only the second occurence of two similar objects?
Because a Map contains a set of key-value pairs. You can only have one value per key. In the constructor, each array is represents [key, value]). The second bit of data with the key 'name' overwrites the first one.
Set returns all three objects even though first two keys and values being same, while it supposed to delete one of them.
A set stores a set of unique values. Each array (like ['name', 'stack']) is one value.
Because Sets are like arrays - they just store the values in a list. Therefore, the constructor will add all three arrays to the new Set as values. The Map constructor is similar to Object.fromEntries - the first item in each sub-array is the key, the second the value. You can't store keys in a Set, only values - so the two items have to be exactly the same, and a primitive, to be excluded from the Set.
A Map is a container for key-value pairs. In your input, name and domain will become keys. Since a key can only exist once, the key name gets deduplicated.
A Set is an array of values which deduplicates the values themselves. Since there aren't any identical values in your input, all are retained.

Can you give an object a key in javascript?

If you have an array of objects like
[{rID:53, name:Roger, age:43},{rID:12, name:Phil, age:22}]
is it possible instead to give each a object a key like
[53:{name:Roger, age:43},12:{name:Phil, age:22}]
?
I understand that each object has an index number, but I'm looking for a way to find objects not based on their index pos, and preferably without having to loop through until you find an object with rID=53 type thing.
I'd be using PKs from mysql rows to give each object it's key.
Cheers
If you want an unordered collection of variables with arbitrary keys. Then use an object.
{"53":{name:Roger, age:43},"12":{name:Phil, age:22}}
Arrays can have only numeric keys, but if you want to assign a value to an arbitrary position, you have to do so after creating the array.
var some_array = [];
some_array[53] = {name:Roger, age:43};
some_array[22] = {name:Phil, age:22};
Note that this will set the array length to 54.
Note that in both cases, you can't have multiple values for a given property (although you could have an array of values there).
You need an object for that.
{
53: {
name: "Roger",
age: 43
},
12: {
name: "Phil",
age: 22
}
}
No. You cannot have a key and an index in a js array. Arrays only have indices, Objects only have keys. There is no such thing like a associative array in JavaScript. If the order (of your original array) does not matter, you can use an object though:
{53:{name:"Roger", age:43},12:{name:"Phil", age:22}}
You can use objects to do this
var map = {"53":{"name": "Roger", "age": "43"},"12":{"name": "Phil", "age": "22"}};
Then access the value like an array (note, i'm using string because that's what keys are stored as, strings, you can access it using an integer, but it will just be converted to a string when searching for the property anyway):
map["53"]
You can also loop through this map object:
for (var key in map) {
var value = map[key];
}

Issue Reversing Array of Objects with JS

I'm parsing JSON and getting an array of objects with javascript. I've been doing this to then append an element for each object:
for(o in obj){ ... }
But I realized that for a certain situation I want to go backwards through the array. So I tried this before the for loop:
obj = obj.reverse();
However this isn't reversing the order of the objects in the array. I could simply put a count variable in the for loop to manually get the reverse, but I'm puzzled as to why reverse doesn't seem to work with object arrays.
There's no such thing as an "object array" in JavaScript. There are Objects, and there are Arrays (which, of course, are also Objects). Objects have properties and the properties are not ordered in any defined way.
In other words, if you've got:
var obj = { a: 1, b: 2, c: 3 };
there's no guarantee that a for ... in loop will visit the properties in the order "a", "b", "c".
Now, if you've got an array of objects like:
var arr = [ { a: 1 }, { b: 2 }, { c: 3 } ];
then that's an ordinary array, and you can reverse it. The .reverse() method mutates the array, so you don't re-assign it. If you do have an array of objects (or a real array of any sort of values), then you should not use for ... in to iterate through it. Use a numeric index.
edit — it's pointed out in a helpful comment that .reverse() does return a reference to the array, so reassigning won't hurt anything.
That's because the for (o in obj) doesn't iterate the array as an array, but as an object. It iterates the properties in the object, which also includes the members in the array, but they are iterated in order of name, not the order that you placed them in the array.
Besides, you are using the reverse method wrong. It reverses the array in place, so don't use the return value:
obj.reverse();

push associative array error?

I have to push elements in an associative array from another array after some processing and I'm doing something this:
for(var i in this.aNames) {
var a = this.aNames[i];
// some processing on a
aList[i] = a;
aList.push(i);
}
But it's not giving me the proper array.
EDIT :
Here aNames is an associative array like this
'1232':'asdasdasd',
'6578':'dasdasdas'
...... and so on of about 100 elements.
I'm using for here as I want to do some changes in every element of the array.
Then I'm displaying the result array on the page but it's showing the key value together with the array data.
I.e. it should only display asdasdasd or asdasdasd but it's displaying keys too, like 1232 asdasdasd 6578 dasdasdas.
There are multiple things which may go wrong...
Primarily, make sure that this is pointing to the correct context and that this.aNames is actually returning a complex object (associative array).
Also, what's aList? Is it an array? If it is, push should append your array with the key of the current member (the member's name).
If you want to append the values of the members on your source object, you need to do something like this:
var obj = {name: 'dreas'},
arr = []; // arr is an array
arr.push(obj["name"]); // arr now contains a single element, 'dreas'
In your for..in construct, you are both adding elements to an alleged array (aList) with push but also creating new members on your array (with the subscript notation, aList[i] = "asd" since i in this case (for..in iteration) refers to the member's name).
So, what you need to do is decide if you want to add elements to an array or members to an object, not both.
If you just want to clone an array, use a for loop. If on the other hand you want to clone an object, it's not that trivial because members can also be complex objects containing their own members, and simply doing arr[i] = obj.member will only copy a pointer to arr[i] if member is a complext object, not a value type.
Just to make sure my terminology is understandable:
var anObject = {name: "dreas"},
anArray = [1,2,3];
anObject["name"] <= member (results in "dreas")
anArray[1] <= element (results in 2)

How do I access the first key of an ‘associative’ array in JavaScript?

I have a js 'associative' array, with
array['serial_number'] = 'value'
serial_number and value are strings.
e.g. array['20910930923'] = '20101102'
I sorted it by value, works fine.
Let's say I get back the object 'sorted';
Now I want to access the first KEY of the 'sorted' array.
How do I do it? I can't think I need an iteration with
for (var i in sorted)
and just stop after ther first one...
thanks
edit: just to clarify, I know that js does not support associative arrays (that's why I put it in high commas in the Title).
2021 Update
Since ES6, properties with string keys are enumerated in insertion order. Here's a nice summary. My original answer from 2010 was correct at the time and is preserved below:
Original answer
JavaScript object properties are specified to have no order, much though many people wish it were different. If you need ordering, abandon any attempt to use an object and use an Array instead, either to store name-value objects:
var nameValues = [
{name: '20910930923', value: '20101102'},
{name: 'foo', value: 'bar'}
];
... or as an ordered list of property names to use with your existing object:
var obj = {
'20910930923': '20101102',
'foo': 'bar'
};
var orderedPropertyNames = ['20910930923', 'foo'];
Try this:
// Some assoc list
var offers = {'x':{..some object...}, 'jjj':{...some other object ...}};
// First element (see attribution below)
return offers[Object.keys(offers)[0]];
// Last element (thanks to discussion on finding last element in associative array :)
return offers[Object.keys(offers)[Object.keys(offers).length - 1]];
Actually JavaScript doesn't support associative arrays, so you can't loop through it in an implied order (e.g. you can't access it via the indexer property array[0] won't access the first element in your object). The syntax is what makes it look like it does, but in reality it doesn't. So you have no "Order" to your objects.
http://www.hunlock.com/blogs/Mastering_Javascript_Arrays
Javascript does not have, and does not
support Associative Arrays. However…
All arrays in Javascript are objects
and Javascript's object syntax gives a
basic emulation of an associative
Array. For this reason the example
code above will actually work. Be
warned that this is not a real array
and it has real pitfals if you try to
use it. The 'person' element in the
example becomes part of the Array
object's properties and methods, just
like .length, .sort(), .splice(), and
all the other built-in properties and
methods.
Just thinking off the top of my head, but could you have another array with the key value pairs swapped?
So the answer would be arrayKeyValueReversed['20101102'] = '20910930923';
When you sort the array, use the first item (array[0]) as the key to get the value in the arrayKeyValueReversed.

Categories