Loop through json object to get values of particular key [duplicate] - javascript

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)

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

Efficient way to get object from array based on key [duplicate]

This question already has answers here:
Find a value in an array of objects in Javascript [duplicate]
(20 answers)
Get JavaScript object from array of objects by value of property [duplicate]
(17 answers)
Closed 4 years ago.
I have an array of objects as:
0: {id: "1", name: "Tab1", address: "123 Street"}
1: {id: "2", name: "Tab2", address: "456 Avenue"}
2: {id: "3", name: "Tab3", address: "789 st"}
I want to grab a particular object from the above array based on the "name" key. For example, if I pass the key as "Tab1" it should return me:
0: {id: "1", name: "Tab1", address: "123 Street"}
I can loop through the array and get the values but wanted to know is there any simpler/efficient way to get the desired data.
You can use Array.prototype.find like this
const searchArray = key => array.find(({name})=> {
return name === key;
});
console.log(searchArray("Tab1"));

javascript array find value base on id [duplicate]

This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
Closed 4 years ago.
I have an array of json objects:
[ {id:0, name:'A'}, {id:1, name:'B'}...{id:n, name:'N'} ]
How do i get the value (name) base on a given id, without iterating the array? Perhaps using map or some filter method...
const arr = [ {id:0, name:'A'}, {id:1, name:'B'},{id:3, name:'N'} ];
const inputId = 1;
const foundObj = arr.find(({ id }) => id === inputId);
if (foundObj) console.log(foundObj.name);
This still does iterate the array internally, though (as any method will).
This find method will find object based on your object property and value.
ArrayName.find(x => x.id === 0);
let array = [ {id:0, name:'A'}, {id:1, name:'B'}, {id:'n', name:'N'} ]
//To search in array we must iterate. But if you want to optimise performance for multiple searches you can map it to object by id.
let map = array.reduce((acc,element)=>{acc[element.id]=element;return acc;},{})
console.log(map[0])
console.log(map[1])
console.log(map.n) //As n was used as id.
Maps take one iteration to construct. Value retrieval thereon is sublinear.
// Input.
const input = [{id: 0, name:'A'}, {id: 1, name:'B'}, {id: 13, name:'N'}]
// To Map.
const toMap = (A) => new Map(A.map(x => [x.id, x]))
// Output.
const output = toMap(input)
// Proof.
console.log(output.get(0))
console.log(output.get(1))
console.log(output.get(13))
When you want to find an element in a collection, array might not be the best choice, objects or maps are much better in that case.
Each time you have to find an element, you would have to iterate over the array which would take O(n) time.
To avoid this, you could have an API layer in the middle, to convert your array into an a data structure which maps values by unique keys. You could achieve this by a plain Javascript Object.
That way you could find your element by id in O(1) without any iteration.
//original data
let arr = [ {id:0, name:'A'}, {id:1, name:'B'}, {id:2, name:'N'} ];
//convert it into object
let obj = arr.reduce((acc, curr) => {
acc[curr.id] = curr;
return acc;
}, {});
//modified data
{ 0: { id: 0, name: 'A' },
1: { id: 1, name: 'B' },
2: { id: 2, name: 'N' } }
//Now, you can look up value on any id as
obj[id].name;

Access object key with a string value [duplicate]

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

Get an object from an array on predicate in Javascript [duplicate]

This question already has answers here:
javascript filter array of objects
(8 answers)
Closed 7 years ago.
I have the following array of objects :
var objs = [{id: 1, name: 'foo', ...},
{id: 2, name: 'bar', ...},
{id: 3, name: 'baz', ...}];
and this variable :
var matcher = 'bar';
What is the easiest way to get the object that has the matcher equals to its name ?
Using this matcher the result should be :
{id: 2, name: 'bar', ...}
The easiest way is to use filter function
var objs = [{id: 1, name: 'foo'},
{id: 2, name: 'bar'},
{id: 3, name: 'baz'}];
var matcher = 'bar';
var result = objs.filter(function(obj) {
return obj.name === matcher;
});
console.log(result); // [{id: 2, name: 'bar'}]
console.log(result[0]); // {id: 2, name: 'bar'}
The easiest way is probably using a library which allows some higher level functions on objects, such as filter.
Such libraries are for example underscore and lodash, both reserving the _ sign for use, with which you'd write:
_(objs).filter(function(element){return element.name === matcher})[0];
(The filter function returns the elements of an array or objects for which the given filtering function returns true - in this case, you're checking whether the name equals your matcher. The return value is an array of these elements, hence the [0] part)
EDIT: I didn't notice you had an array to begin with, then you don't even need an external library, arrays by default have the filter method on them.

Categories