Getting the Key of a Key Value Pair [duplicate] - javascript

This question already has answers here:
How to get a key in a JavaScript object by its value?
(31 answers)
Closed 4 years ago.
I have a key value pair array in js
var tabList = {0:'#description', 1:'#media', 2:'#attributes', 3:'#calendar', 4:'#pricing'}
I'm using the keys to get the values in my code
ie. tabList[2] returns #attributes
I thought I could do the same in reverse to get the key
tabList[#media] and have it return 1
But this doesn't work
How can I fetch the key with only the value as input?

There are plenty of solutions here Swap key with value JSON
I will flip key with values 1st
var tabList = {0:'#description', 1:'#media', 2:'#attributes', 3:'#calendar', 4:'#pricing'}
let flipped=Object.assign({}, ...Object.entries(tabList).map(([k,v]) => ({ [v]: k })))
console.log(flipped);
console.log(flipped['#description']);

Related

Variation: Find the object with the highest value in Javascript [duplicate]

This question already has answers here:
Getting key with the highest value from object
(9 answers)
Closed 9 months ago.
In Finding the max value of an attribute in an array of objects there are many (great) answers that report the highest value in an array, but they leave out the option that the object with the highest value would be the desired result to report.
I'm looking for the best way to search for the highest value in an array and return the object that has this value. For example, the expected result of checking this array:
{
"Intent": {
"FileComplaint": 0.000,
"UnsubscribeMe": 0.995,
"TrackRefund": 0.001,
"AskSwitchAccount": 0.00
}
would be: "UnsubscribeMe" or "UnsubscribeMe": 0.995.
Anyone who can help?
Edit:
I found a question that is better formulated than mine and it has great answers:
Getting key with the highest value from object
const obj={Intent:{FileComplaint:0,UndermineGovernment:0.45,UnsubscribeMe:.995,TrackRefund:.001,AskSwitchAccount:0}};
// Get the entries as a nested array of key/value pairs
const entries = Object.entries(obj.Intent);
// Sort the entries by value (index 1),
// and then pop off the last entry destructuring
// the key/value from that array in the process
const [key, value] = entries.sort((a, b) => a[1] > b[1]).pop();
// Log the resulting object
console.log({ [key]: value });

How to identify part of the localStorage key in JavaScript? [duplicate]

This question already has answers here:
html5 window.localStorage.getItemItem get keys that start with
(4 answers)
Closed 1 year ago.
I have following types of keys in my localStorage,
Key: Designer-96, Value: true
Key: Designer-76, Value: true
On Page_Load() I want to identify if localStorage contains any keys that start with Designer word, if that's the case then I want to execute certain logic.
Is it possible to iterate through the keys of localStorage in JavaScript and find part of the matching key?
You can get all keys of localStorge using
Object.keys(localStorage)
and you can then use some to check for the existence of a key starts with Designer
const ls = localStorage;
ls.setItem("Designer-96", true);
ls.setItem("Designer-76", true);
const keys = Object.keys(ls);
if (keys.some((k) => k.startsWith("Designer"))) console.log("Key is present");
else console.log("Key is not present");

Drop all duplicates from array using JavaScript [duplicate]

This question already has answers here:
remove all elements that occur more than once from array [duplicate]
(5 answers)
How to remove all duplicates from an array of objects?
(77 answers)
Completely removing duplicate items from an array
(11 answers)
Closed 1 year ago.
I have an array of objects with input like below
var jsonArray1 = [{id:'1',name:'John'},{id:'2',name:'Smith'},{id:'3',name:'Adam'},{id:'1',name:'John'}]
The id 1 appears twice and I would like to drop all duplicate records .i.e. my output should look like
[{id:'2',name:'Smith'},{id:'3',name:'Adam'}]
Can you please guide/direct me in how I can drop all duplicate records
Create Map from an array where key of the Map is your desired id, duplicated won't be preserved (only last occurrence will). After just take the values from Map.
Removing all of occurrences of duplicates (this is what OP wanted):
const input = [{id:'1',name:'John'},
{id:'2',name:'Smith'},
{id:'3',name:'Adam'},
{id:'1',name:'John'}]
const res = input.filter((x, i, arr) =>
arr.filter(e => e.id === x.id).length === 1)
console.log(res)
Preserving 1 occurrence of duplicates:
const input = [{id:'1',name:'John'},
{id:'2',name:'Smith'},
{id:'3',name:'Adam'},
{id:'1',name:'John'}]
const unique = [...new Map(input.map(item => [item.id, item])).values()]
console.log(unique)

convert array of hashes to array of values in javascript [duplicate]

This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 2 years ago.
I am an array of hashes and I want to convert it to array of values something like this
array of hashes [{text: "James"},{text: "developer"}]
convert this to
array of values ["James", "Developer"]
Please help me achieve this in javascript.
Using Object.values, you can get the values of each object.
const input = [{text: "James"},{text: "developer"}];
const output = input.flatMap((item) => Object.values(item));
console.log(output);

Creating dictionary using python from javascript var data [duplicate]

This question already has answers here:
Convert [key1,val1,key2,val2] to a dict?
(12 answers)
Make dictionary from list with python [duplicate]
(5 answers)
Convert list into a dictionary [duplicate]
(4 answers)
Closed 4 years ago.
trying to figure out how to do this and have yet to find a good solution. I pulled this data out of an XML response. It was in a var tag. Now what I would like to do is create a dictionary out of it. The domain.com should be paired with the number right listed behind it.
This is the data:
[
'cb131.domain1.com', '147827',
'cb143.domain2.com', '147825',
'cb175.domain1.com', '147454',
'cb190.domain.com', '146210',
'cb201.domain.com', '146208',
'cb219.domain.com', '146042',
'cb225.domain.com', '146282',
'cb900.domain.com', '148461',
'cb901.domain.com', '148493',
'cb902.domain.com', '148495',
'cb903.domain.com', '148497',
'cb904.domain.com','148499',
'cb905.domain.com', '148501',
'cb906.domain.com', '148503',
'cb907.domain.com', '148505',
'cb908.domain.com', '148507',
'cb909.domain.com', '148509'
]
So for example cb131.domain1.com should be paired with 147827, cb143.domain2.com paired with 147825 and so on.
Drawing a blank on a good quick solution on how to do this. Hopefully someone can help.
Thanks!
Edited with answer I choose below:
I choose this answer and also to help anyone else I add a nice way to print out the results (data is the string I obtained):
import ast
i = iter(ast.literal_eval(data))
dic = dict(zip(i, i))
for key , value in dic.items():
print(key, " :: ", value)
This should do it. Assuming the list is saved to a variable l:
keys = l[::2]
vals = l[1::2]
dic = dict(zip(keys, vals))
You can create an iterator from the list after using ast.literal_eval to parse it from the input text, zip the iterator with itself, and pass the generated sequence of tuples to the dict constructor:
import ast
i = iter(ast.literal_eval(data))
dict(zip(i, i))
Assuming you have the above in a python array called data, you can do:
new_data = []
for i in range(0, len(data), 2):
new_data.append((data[i], data[i+1]))
Now new_data would be a list of tuples. You could certainly create a better data structure to hold these pairs if you want.
I do not yet know Python that I can write a snippet, but:
initialize an empty dictionary in Python
create a for loop counting index from 0 to length of your array in steps of two.
inside add a dictionary entry with key of value at index and value at index + 1
perhaps check for duplicates
Does this answer help you?
This is Python - quickly google'd:
dictionary = { }
for idx in range(0, len(data), 2)
dictionary[data[idx]] = data[idx + 1]

Categories