Access Object property using key name within map - object

I have below array of object
const reports = [{id:3, name:'three', description:'three d', other: 'other 3'}, {id:2, name:'two', description:'two d', other: 'other 2'}];
and I want to filter out only 2 property of each object and below is my desired output
[{id:3, name:'three'}, {id:2, name:'two'}];
so tried this way
const reportList = reports.map((report) => {id,name} );
console.log(reportList);
throw error
ReferenceError: id is not defined
even I can achieve this by using this approach
this.reportList = reports.map((report) => ({
id: report.id,
name: report.name,
description: report.description
}));
but here I need to write extra code, I want to use object accessor using key, can I achieve anyway?

You must wrap the returning object literal into parentheses. Otherwise curly braces will be considered to denote the function’s body. The following works:
const reports = [{
id: 3,
name: 'three',
description: 'three d',
other: 'other 3'
}, {
id: 2,
name: 'two',
description: 'two d',
other: 'other 2'
}];
const reportList = reports.map(({id, name}) => ({
id,
name
}));
console.log(reportList);
Reference: Returning object literals by MDN

Related

Select Menu Discord JS | How can i use array in .addOptions?

I would like to map an array inside .addOptions.
Basically, I would like to add a value { } to addOptions by taking the values of an object or array.
Examples:
let menu = new SelectMenuBuilder()
.setCustomId('select')
.setPlaceholder('Nothing selected')
.addOptions(arrayt.map(song => label: song.name, description: song.formattedDuration, value: blabla)
You are missing curly brackets in your map function. The function should look something like this
const songs = [
{
name: 'Song 1',
formattedDuration: 2
},
{
name: 'Song 2',
formattedDuration: 5
},
{
name: 'Song 3',
formattedDuration: 6
}
]
const menu = new SelectMenuBuilder()
.setCustomId('select')
.setPlaceholder('Nothing selected')
.addOptions(songs.map(song => { return {label: song.name, description: song.formattedDuration }}))
The values should be in the form of a string, not integer or double, whatever you are giving, use toString() on them.
const row = new ActionRowBuilder().addComponents(
new StringSelectMenuBuilder()
.setCustomId('select')
.setPlaceholder('Nothing selected')
.addOptions(
adana.map(function (curentValue, index) {
return {
label: index.toString(),
value: index.toString(),
}
})
)
)

How to get index value of choice made with Inquirer?

I'm trying to get an integer value from the user when this questions is asked:
let q4 = {
type: 'list',
name: 'manager',
message: 'Who do they report to?',
choices: ['Jen','Rachel','Tania']
};
let answerProcessing = (answer) => {
console.log(answer.manager)
}
but I can't figure it out from the documentation and I don't see any similar questions to this one. Perhaps it's really obvious but I can't get a non-string response.
You can give your choices a name and value.
The name will be output in the terminal.
The value can be whatever simple value you like it to be, like a number, or a short for the name.
let q4 = {
type: 'list',
name: 'manager',
message: 'Who do they report to?',
choices: [
{
name: 'Jen',
value: 1,
},
{
name: 'Rachel',
value: 2,
},
{
name: 'Tania',
value: 3,
}
]
};
let answerProcessing = (answer) => {
console.log(answer.manager) // outputs 1, 2, or 3
}
Figured it out:
console.log(q4.choices.indexOf(answer.role));
This will give the index value.
Leaving it up because I couldn't see other questions like it.

get RealmResults in array instead of object in NodeJs

I have a simple Schema
const MediaElementSchema = {
primaryKey: 'id',
name: 'MediaElement',
properties: {
id: 'int',
type: 'string',
path: 'string'
}
}
When I try to get all:
let elements = realm.objects('MediaElement')
Realm returns the results in an object like below:
{"0": Record1, "1" : Record2, etc}
is there a way for realm to return an array of the elements like:
[Element1, Element2, etc]
I checked the documentation but didn't find anything relevant about the return type.
https://realm.io/docs/javascript/latest
You could just use plain old javascript to convert object into array.
let elements = {'0': 'Record1', '1' : 'Record2'};
elements = Object.keys(elements).map(key => elements[key]);
console.log(elements); // ["Record1", "Record2"]

Access a specific property in Object.keys adonis.js (Node.js)

I have a query that returns an array, with Object.key (array) .foreach I am iterating, I want to know the value of a property in specific array.
Example:
Object.keys(arreglo).forEach(function(key) {
console.log(arreglo[key]);
});
The output is:
name: "Pepito",
Surname: "Perez"
I want to know how to get only the value of the surname
I know it will not work but it would be something like:
console.log(arreglo[key].surname);
You can use Array.forEach on the original array as shown below. You can even extract the fields you are interested using Array.map.
// let's assume the arrary you got from your query is in this format
const arreglo = [
{ firstname: "fn1", surname: "ln1"},
{ firstname: "fn2", surname: "ln2"},
{ firstname: "fn3", surname: "ln3"}
];
// you can log `surname` for each entry in the array
arreglo.forEach(v => console.log(v.surname));
// you can use map to transform the array to just have `surname` using array.map()
const surnames = arreglo.map(v => v.surname);
console.log(surnames);
Is this what you are looking for
const object1 = {
a: {firstname:"sali",lastname:"mali"},
b: {firstname:"sali",lastname:"mali"},
c: {firstname:"sali",lastname:"mali"}
};
Object.keys(object1).forEach(function(key){console.log(object1[key].lastname)});

Issue with concurrent (iterated) invocations of a function that calls Promise.all()

This example is a simplification, but hopefully demonstrates my problem. I suspect I am missing something obvious re: closure here.
The issue is that results being returned from my aggregation function below include the final set of personParams i.e. those resulting from the final iteration of the forEach , not the set of personParams that the function was called with.
let promiseArray = []; // top level array of promises
let globalParams = { date: "2018-05-20" };
let people = [
{name: "Tom",
location: "Philadelphia"},
{name: "Bob",
location: "Austin"},
{name: "John",
location: "Philadelphia"}
];
people.forEach( person => {
// Create indivdiualized parameter set
let personParams = globalParams;
personParams.name = person.name;
personParams.location = person.location;
// Push promise to array
promiseArray.push(assembleResults(personParams));
});
Promise.all(promiseArray).then( results => {
console.log("Final Output:", results);
})
// individual data aggregation function
function assembleResults(iterationParams) {
let promise1 = Promise.resolve({data: "Type A data about " + iterationParams.name});
let promise2 = Promise.resolve({data: "Type B data about " + iterationParams.name});
let promise3 = Promise.resolve({data: "Type C data about " + iterationParams.name});
return Promise.all([promise1, promise2, promise3, iterationParams])
}
Updated with executable Fiddle # JSFiddle https://jsfiddle.net/shaunhurley/9r5k6j0c/
My expectation is that each iteration of assembleResults() is going to return an array that looks like:
[{data: "Type A data about <person's name>"},
{data: "Type B data about <person's name>"},
{data: "Type C data about <person's name>"},
{date: "2018-05-20", name: "<person's name>", location: "<location>"}]
Where each array will have name set to "Tom", "Bob" & "John" respectively. The final output would be an array or arrays per below.
[{data: "Type A data about Tom"},
{data: "Type B data about Tom"},
{data: "Type C data about Tom"},
{date: "2018-05-20", name: "Tom", location: "Philadelphia"}]
[{data: "Type A data about Bob"},
{data: "Type B data about Bob"},
{data: "Type C data about Bob"},
{date: "2018-05-20", name: "Bob", location: "Austin"}]
[{data: "Type A data about John"},
{data: "Type B data about John"},
{data: "Type C data about John"},
{date: "2018-05-20", name: "John", location: "Philadelphia"}]
The actual result is that, while the correct data sets are being returned, the parameter set included in each array is showing the last/final parameter set generated i.e. name == "John" and location == "Philadelphia"
[{data: "Type A data about Tom"},
{data: "Type B data about Tom"},
{data: "Type C data about Tom"},
{date: "2018-05-20", name: "John", location: "Philadelphia"}]
[{data: "Type A data about Bob"},
{data: "Type B data about Bob"},
{data: "Type C data about Bob"},
{date: "2018-05-20", name: "John", location: "Philadelphia"}]
[{data: "Type A data about John"},
{data: "Type B data about John"},
{data: "Type C data about John"},
{date: "2018-05-20", name: "John", location: "Philadelphia"}]
Any thoughts would be greatly appreciated...
Thanks!
Shaun
people.forEach(person => {
let personParams = globalParams;
personParams.name = person.name;
promiseArray.push(assembleResults(personParams));
});
In the above code block you called person.name where I can see each person is a String. So you are getting undefined instead of the person's name. I think it should be personParams.name = person.
And getResultsA getResultsB and getResultsC of assembleResults() function should not return any data unless you have some person called undefined.
I guess it's a dummy code you have posted. Posting the real code would have helped me answering more precisely.
Modification
Bellow code would do your job:
people.forEach((person) => {
// Create indivdiualized parameter set
const personParams = {
date: globalParams.date,
name: person.name,
location: person.location
}
// Push promise to array
promiseArray.push(assembleResults(personParams));
});
Explaining how did it work would take too long and I guess you already know why did it behave like that. Please google 'JavaScript object creation'.

Resources