Access object key with a string value [duplicate] - javascript

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 5 years ago.
I have a hand-typed database with an object that has categories and a list of words for each category, as below:
var words =
{
sports: [
'baseball', 'football', 'volleyball', 'basketball', 'soccer'],
animals: [
'dog', 'cat', 'elephant', 'crocodile', 'bird'],
entertainment: [
'netflix', 'movies', 'music', 'concert', 'band', 'computer']
}
My HTML has a bootstrap dropdown that will display all categories based on that list. I have the code working to give me the value of the category clicked as a string: as below:
$(document).on('click', '.dropdown-menu li a', function () {
var selectedCategory;
selectedCategory = $(this).text();
//setting value of category to global variable
categorySelected = selectedCategory;
});
I need to be able to find the key in my database from that value.
The problem is that I can't access words."animals"
I need to take the quotation marks off my string to get the list of words like this:
words.animals
How do I do this? I've tried replace() but it doesn't work.

It seems like you're trying to access the list of values corresponding to the category in your words object. Keys can be strings, so words['animals'] would be an example of getting your list of animals.
JavaScript allows variables to be used as keys as well, so you can access it as follows:
words[categorySelected]

You can pass the text(selected value from drop down) to a function to find the key
var words = {
sports: [
'baseball', 'football', 'volleyball', 'basketball', 'soccer'
],
animals: [
'dog', 'cat', 'elephant', 'crocodile', 'bird'
],
entertainment: [
'netflix', 'movies', 'music', 'concert', 'band', 'computer'
]
}
// function to find the key
function findKey(selText) {
//loop through the object
for (var keys in words) {
//get the array
var getArray = words[keys]
//inside each array check if the selected text is present using index of
if (getArray.indexOf(selText) !== -1) {
console.log(keys)
}
}
}
findKey('music')

Related

What is the easiest way to match/consolidate two arrays of data that have relationships? [duplicate]

This question already has answers here:
Merge 2 arrays of objects
(46 answers)
Closed 1 year ago.
Say I have two data arrays for a ticketed event. One is attendees:
[
{name: 'Jack', ticket_code: 'iGh4rT'},
{name: 'Lisa', ticket_code: 'it1ErB'}
]
The other is tickets:
[
{code: 'iGh4rT', name: 'General Admission'},
{code: 'it1ErB', name: 'VIP'}
]
Now say I want to display a table like this:
Name
Ticket Name
Jack
General Admission
Lisa
VIP
I am struggling with doing this efficiently. I can display a table with one array no problem like something like this:
for (let i = 0; i < attendees.length; i++){
const row = `<tr>
<td>${attendees[i].name}</td>
<td>${attendees[i].ticket_code}</td>
</tr>`
document.getElementById('TableBody').innerHTML += row
I need to somehow 'query' the tickets array with the code from the attendees array for that particular person, get the name of the ticket, and supplant the ticket name instead of the code.
With SQL something like this is easy, but is one able to "query" an array and get a specific property? Should I construct a whole new array with the needed info? What is the best way to do this that would work for large unordered datasets?
You could take one of your array as an object with code as key for the object and map the other array with wanted data and the previous stored data from the object.
const
attendees = [{ name: 'Jack', ticket_code: 'iGh4rT' }, { name: 'Lisa', ticket_code: 'it1ErB' }],
tickets = [{ code: 'iGh4rT', name: 'General Admission' }, { code: 'it1ErB', name: 'VIP' }],
ticketsByCode = Object.fromEntries(tickets.map(o => [o.code, o])),
table = attendees.map(({ name, ticket_code }) => [name, ticketsByCode [ticket_code].name]);
console.log(table);
try this:
let a = [
{name: 'Jack', ticket_code: 'iGh4rT'},
{name: 'Lisa', ticket_code: 'it1ErB'}
];
let b = [
{code: 'iGh4rT', name: 'General Admission'},
{code: 'it1ErB', name: 'VIP'}
];
let c = b.map(item => {
return {
tiketName: item.name,
...a.find(itemA => itemA.ticket_code == item.code)
}
});
console.log(c);

Filter multidimensional array with objects

With an array like the following, how can I filter objects based on the texts.id? For example if I wanted to return this very same array without the texts object reffering to the id 123 how would I go about it? I have access to the id I want to filter out and also the name of the object where its located. I have been trying to figure this out but I am not sure this is doable with the filter method only. Thanks in advance to anyone that helps.
[
0: Object {
name: 'Name 1',
texts[
0: Obj{
id: '123',
body: 'test message'
},
1: Obj{
id: '456',
body: 'test message 2'
}
]
},
1: Object {
name: 'Name 2',
texts[
0: Obj{
id: '789',
body: 'test message3'
},
1: Obj{
id: '101112',
body: 'test message 4'
}
]
}
]
It's not totally clear to me whether you want to remove the entire outer object where the texts array contains an object with a certain id (i.e: in your example, this would remove the whole object with name 'Name 1'), or if you just want to remove the object in the texts array which has a certain id (i.e: leaving the outer object, just removing the object in texts with id 123).
The former has been answered by #lissettdm above, but if it's the latter, you could do something like this:
const filter = "123";
entry.forEach(item => item.texts = item.texts.filter(text => text.id !== filter));
Yes, it is possible using Array.prototype.filter() and Array.prototype.find()
const entry = [{name: "Name 1",texts: [{id: "123",body: "test message"},{id: "456",body: "test message 2"}]},{name: "Name 2",texts: [{id: "789",body: "test message3"},{id: "101112",body: "test message 4"}]}];
const filter= "123";
const output = entry.filter(item => item.texts.find(text=> text.id===filter));
console.log(output);

Loop through json object to get values of particular key [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.
0: {id: "7B5B201E-35AA-48A1-B919-002445319F8B", name: "Naman Sabarwal"}
1: {id: "EA6672BA-4F7A-4214-A37F-00716CE698C9", name: "me name"}
2: {id: "01F29920-9206-42DF-8151-00A6A080C501", name: "Nitesh Negi"}
I want to get a list such that the list contains only the name key values.
listOfNames = ['sonu singh','me name','harman jain']
How to get all the values of the key 'name'?
listOfNames = jsonValues.map(x=>x.name)
You can try as follow.
let data = [
{id: "7B5B201E-35AA-48A1-B919-002445319F8B", name: "Naman Sabarwal"},
{id: "EA6672BA-4F7A-4214-A37F-00716CE698C9", name: "me name"},
{id: "01F29920-9206-42DF-8151-00A6A080C501", name: "Nitesh Negi"}
]; // assume the data is in array
let result = data.map( d => d.name );
console.log(result);
if it is json object like
details = [{id:"",name:""},{id:"",name:""},{id:"",name:""}]
you can use map function like
function getnames(){
let names = []
details.map((detail)=>{
names.push({name:detail.name})
return names
}
to shorten this
let names = values.map(value=>return value.name)

Javascript: How to get the length of object but for a specific property?

How to get furniture children count that has property 'chair'
Is there way for example like house.furniture.length(chair) ?
Or do I need to use .filter to filter the ones I want and than apply .length to the filtered array?
Object:
house =[
furniture: [{
chair: {name: 'Sun'},
chair: {name: 'vii'},
table: {name: 'bing'},
}]
]
As #boovad has said, an object cannot have two properties with the same name. Also an array cannot have non-numeric keys. You therefore need to restructure your object.
I'd suggest something like this:
var house = {
furniture: {
chairs: [{
name: 'Sun'
}, {
name: 'Vii'
}],
tables: [{
name: 'Bing'
}],
},
};
Then to find the number of each type of furniture:
house.furniture.chairs.length; // 2
house.furniture.tables.length; // 1

Javascript splicing an array just replaces the value instead of removing it [duplicate]

This question already has answers here:
Javascript oddness with array of objects and indexOf
(2 answers)
Closed 6 years ago.
I have a menu containing a list of dishes. i want to be able to remove the dishes from the menu, i approached this by splicing the index of the dish id in the menu array.
But instead of removing the value and shortening the array, it just replaces the value by the last value in the array.
In a menu with 4 dishes, after removing 3 of them, the array still contains 4 values, all of them are the same.
$scope.fjernRet = function(ret, menu) {
//console.log(ret._id)
var index = menu.retter.indexOf(ret._id);
if (index > -1) {
menu.retter.splice(index, 1)
}
menuService.update(menu);
socket.syncUpdates('menu', $scope.menuer);
}
menu.retter could look like
[{
_id: '56e827ba0ec7a8d02bf7747d',
name: 'test',
info: 'testinfo',
type: 'kød',
active: true
}, {
_id: '56e827ba0ec7a8d02bf77473',
name: 'test3',
info: 'testinfo3',
type: 'kød',
active: true
}, {
_id: '56e827ba0ec7a8d02bf77474',
name: 'test4',
info: 'testinfo4',
type: 'salat',
active: false
}];
Replace this line:
var index = menu.retter.indexOf(ret._id);
by this:
var index = menu.retter.map(function(x){
return x._id
}).indexOf(ret._id);
The Array.map() will return a mapped array with only the _id's, then your .indexOf() can work.
Hope it helps.

Categories