Firebase extract name of object - javascript

I have a simple question today.
I retrieve data from my firebase database:
const response = await fetch('For pricacy purpose I replaced this link to my firebase database.');
const resData = await response.json();
console.log(resData);
Also I log the results in the console, the following text is what I retrieve:
Object {
"-MPOg49jvG-md0twgj-D": Object {
"id": 1,
},
"-MPTgHoTXzIcY_KpBHkc": Object {
"id": 2,
},
"-MPTgmANDZkMv7f_A9TG": Object {
"id": 4,
},
"-MPTgmc2fuu5XSUawuW7": Object {
"id": 3,
},
}
Now my question: I want to access not the id that is in the objects but rather the "name" of the object itself. If you look at the first element:
"-MPOg49jvG-md0twgj-D": Object {
"id": 1, }
i want to access this "-MPOg49jvG-md0twgj-D" and store it in a constant but I dont know how to do it. Any idea would be appriciated.

If I'm understanding correctly, you already fetched resData as a JavaScript object and want to get the keys? These are some ways that possibly could help you.
const resData = {
"-MPOg49jvG-md0twgj-D": {
id: 1
},
"-MPTgHoTXzIcY_KpBHkc": {
id: 2
},
"-MPTgmANDZkMv7f_A9TG": {
id: 4
},
"-MPTgmc2fuu5XSUawuW7": {
id: 3
}
};
// method 1
console.log(Object.keys(resData));
// method 2
for (const key in resData) {
console.log(key, resData[key]);
}
// method 3
console.log(Object.getOwnPropertyNames(resData));
Hope this can help, please correct me if I got it wrong.

Related

Access and extract values from doubly nested array of objects in JavaScript

I have an array of objects and within those objects is another object which contains a particular property which I want to get the value from and store in a separate array.
How do I access and store the value from the name property from the data structure below:
pokemon:Object
abilities:Array[2]
0:Object
ability:Object
name:"blaze"
1:Object
ability:Object
name:"solar-power"
How would I return and display the values in the name property as a nice string like
blaze, solar-power ?
I tried doing something like this but I still get an array and I don't want to do a 3rd loop since that is not performant.
let pokemonAbilities = [];
let test = pokemon.abilities.map((poke) =>
Object.fromEntries(
Object.entries(poke).map(([a, b]) => [a, Object.values(b)[0]])
)
);
test.map((t) => pokemonAbilities.push(t.ability));
Sample Data:
"pokemon": {
"abilities": [
{
"ability": {
"name": "friend-guard",
"url": "https://pokeapi.co/api/v2/ability/132/"
},
"ability": {
"name": "Solar-flare",
"url": "https://pokeapi.co/api/v2/ability/132/"
}
}
]
}
Then I am doing a join on the returned array from above to get a formatted string.
It just seems like the multiple map() loops can be optimized but I am unsure how to make it more efficient.
Thank you.
There is no need for a loop within loop. Try this:
const pokemon = {
abilities: [{
ability: {
name: 'friend-guard',
url: 'https://pokeapi.co/api/v2/ability/132/'
},
}, {
ability: {
name: 'Solar-flare',
url: 'https://pokeapi.co/api/v2/ability/132/'
}
}]
};
const pokemonAbilities = pokemon.abilities.map(item => item.ability.name).join(', ');
console.log(pokemonAbilities);

Loop to get value based on key name

Below is the JSON response I am getting. From this JSON response, I want to get the value of "fees" based on "detailComponent" with "FULL_FEE" only. But, somehow it gets the last value of "detailComponent" with "SUB_FEE" or others which is not correct.
I am sure not how to make this for loop condition to fix my issue. Can help to guide pls?
let data = {
"status": "SUCCESS",
"result": {
"originData": {
"detailType": "MSG",
"origin": [
{
"details": [
{
"detailComponent": "FULL_FEE",
"fees": 13564.00
},
{
"detailComponent": "SUB_FEE",
"fees": 8207.60
}
]
}
]
}
}
}
var getData = data.result.originData.origin[0].details[0].detailComponent;
console.log('getData: ', getData);
You can convert the array into a dictionary by the key (detailComponent) and the number (fees).
// Create Array
var items = [];
// Loop Through It
data.result.originData.origin[0].details.forEach((el, index) => items[el.detailComponent] = el.fees);
// Test
console.log(items["FULL_FEE"]);

Strapi: Get all nested properties for deeply nested relation

I recently started working with strapi and have been figuring out how to go about content relations and so on... Now I have reached a point when I have multiple content relations dependent on each other.
This is my strucute:
Collection Types:
Categories
Articles
with content relation: Article has one category
Single Types:
Homepage
with content relation: Homepage has many articles
Now what I want to do is to to get all nested properties of a category for articles that are assigned to homepage just by simply making a GET request from /homepage
What I currently get is a json structure like this:
{
"id": 1,
"hero": {
....
},
"featuredArticles": {
....
},
"displayedArticles": [
{
"id": 2,
"category": 5,
}
]
}
What is the expected output:
{
"id": 1,
"hero": {
....
},
"featuredArticles": {
....
},
"displayedArticles": [
{
"id": 2,
"category": [
{
"id": 5,
"title": "Foundation"
}
],
}
]
}
My suspicion is that the properties of categories is basically too nested when trying to fetching from /homepage rather than /articles directly.
I found out that handling this could work with modifying the controllers right in the strapi directory but I haven't figured it out quite.
Strapi Controller Docs
Is here anybody who knows solution to this?
Firstly you'll need a custom controller function for this. In /api/homepage/controllers/homepage.js you can export your custom find function.
There you can define which fields you want to populate:
module.exports = {
find: ctx => {
return strapi.query('homepage').find(ctx.query, [
{
path: 'displayedArticles',
populate: {
path: 'category',
},
},
]);
}
};
For reference see the most recent beta docs:
Customization
Second way: populate it as per requirement
module.exports = {
find: async (ctx) => {
const homePage = await strapi.query('homepage').find(ctx.query);
const categories = await strapi.query('categories').find();
if (homePage[0].displayedArticles) {
homePage[0].displayedArticles.forEach(async (content) => {
if(categories){
content.category = categories.find((category) => {
return category.id === content.category;
});
}
});
}
if (homePage[0].displayedComponents) {
homePage[0].displayedComponents.forEach(async (content) => {
if(categories){
content.category = categories.find((category) => {
return category.id === content.category;
});
}
});
}
return homePage;
}
};

Filter Array Using Partial String Match in Javascript

I have an array of objects where the value I need to filter on is buried in a long string. Array looks like:
{
"data": {
"value": "{\"cols\":[\"parent_sku\"],\"label\":\"Style\",\"description\":\"Enter Style.\",\"placeholderText\":\"Style 10110120103\"}",
"partnerId": 1
}
},
So if I wanted to grab all the partnerId objects where value includes parent_sku how would I do that?
console.log(data.value.includes('parent_sku') returns cannot read property 'includes' of null.
EDIT:
Didn't think this mattered, but judging by responses, seems it does. Here's the full response object:
Response body: {
"data": {
"configurationByCode": [
{
"data": {
"value": "{\"cols\":[\"parent_sku\"],\"label\":\"Style\",\"description\":\"Enter Style.\",\"placeholderText\":\"Style 10110120103\"}",
"partnerId": 1
}
}
I'm passing that into a re-usable function for filtering arrays:
const parentSkuPartners = filterArray(res.body.data.configurationByCode, 'parent_sku');
Function:
function filterArray(array, filterList) {
const newList = [];
for (let i = 0; i < array.length; i += 1) {
console.log('LOG', array[i].data.value.includes('parent_sku');
}
}
The problem is somewhere else. The code you've tried should work to find if a value contains a string – I've added it the snippet below and you'll see it works.
The issue is how you are accessing data and data.value. The error message clearly states that it believes that data.value is null. We would need to see the code around it to be able to figure out what the problem is. Try just logging to console the value of data before you run the includes function.
const data = {
"value": "{\"cols\":[\"parent_sku\"],\"label\":\"Style\",\"description\":\"Enter Style.\",\"placeholderText\":\"Style 10110120103\"}", "partnerId": 1
};
console.log('includes?', data.value.includes('parent_sku'));
You can use data.value.includes('parent_sku') as you have suggested. The issue here is that your object is nested inside an unnamed object.
try:
"data": {
"value": "{\"cols\":[\"parent_sku\"],\"label\":\"Style\",\"description\":\"Enter Style.\",\"placeholderText\":\"Style 10110120103\"}",
"partnerId": 1
}
The problem was some of the values for value were null. Adding an extra conditional fixed it:
if (array[i].data.value !== null) {
Use lodash includes, and lodash filter like
let configurationByCode = [{
data: {
value: {
cols:["parent_sku"],
label:"Style",
description:"Enter Style.",
placeholderText:"Style 10110120103"
},
"partnerId": 1
}
}, {
data: {
value: {
cols:["nothing"],
label:"Style",
description:"Enter Style.",
placeholderText:"Style 10110120103"
},
"partnerId": 2
}
}];
let wantedData = _.filter(configurationByCode, (config) => {
return _.includes(config.data.value.cols, 'parent_sku');
});
console.log( wantedData );
https://jsfiddle.net/76cndsp2/

Mapping data from two dictionary and make a resultant one with specific format in javascript

I have a two dictionaries:
featurePermissionMap = {'2':2,'3':1,'4':1} where key is the feature id and it's value represents the permission type.
Like '2':2 means for a feature id 2 we have a permission 2(Read and Write)
and '3':1 means for a feature id 3 we have a permission 1(Read-Only)
Second Dictionary:
feature_with_sub_feature =
[
{ name: 'FeatureA',
subfeatures: [
{ id: 2, name: 'Feature2' },
{ id: 3, name: 'Feature3' },
},
.......
];
I need a resultant dictionary like below:
read_write_access_feature = {
'read':{},
'write':{}
}
I just want to iterate over feature_with_sub_feature and based on subfeature id, I want output like
read_write_access_feature = {
'read':{'FeatureA':['Feature3',....],......},
'write':{'FeatureA':['Feature2',.....],....}
}
I am trying to achieve this using the two forEach. I am new to javascript.
Any optimized way would be much appreciated.
Any help/suggestions would be much appreciated.
Added function getFeatureWithPermission which will return features with permission passed in parameter. Added code explanation in comment.
call getFeatureWithPermission will required permission as below.
let read_write_access_feature = {
'read': getFeatureWithPermission(1),
'write': getFeatureWithPermission(2)
};
Try it below.
let featurePermissionMap = {'2': 2, '3': 1, '4': 1};
// return features with permission passed in parameter.
function getFeatureWithPermission(permission) {
// use reduce to update & return object as requiment
return feature_with_sub_feature.reduce((a, x) => {
// return object with key as x.name
// value as array of names from subfeatures which have respective permission
// first filter subfeatures for respective permission
// then use map to select only name from subfeatures
a[x.name] = x.subfeatures
.filter(y => featurePermissionMap[y.id] === permission)
.map(y => y.name);
return a;
}, {}); // <- pass empty object as input
}
let feature_with_sub_feature = [{
name: 'FeatureA',
subfeatures: [
{ id: 2, name: 'Feature2' },
{ id: 3, name: 'Feature3' },
]
}];
let read_write_access_feature = {
'read': getFeatureWithPermission(1),
'write': getFeatureWithPermission(2)
};
console.log(read_write_access_feature);

Categories

Resources