Adding additional properties to API results in React [duplicate] - javascript

This question already has answers here:
Add property to an array of objects
(7 answers)
Closed 10 months ago.
I am making an API call in React and I would like to add an additional price property to the results, with each property having a different value for each result.
For example...
API response:
{
id: 456
name: "capuccino",
type: "coffee",
},
{
id: 457
name: "latte",
type: "coffee",
},
{
id: 458
name: "americano",
type: "coffee",
}
Is there a way to dynamically add an additional price property, each with a different value to get the result below?
{
id: 456
name: "capuccino",
type: "coffee",
**price: 5.99**
},
{
id: 457
name: "latte",
type: "coffee",
**price: 10.00**
},
{
id: 458
name: "americano",
type: "coffee",
**price: 8.90**
}

You could create a prices array and use map() and the index to map the price to the correct object.
const response = [{
id: 456,
name: "capuccino",
type: "coffee",
},
{
id: 457,
name: "latte",
type: "coffee",
},
{
id: 458,
name: "americano",
type: "coffee",
}
];
const prices = [2, 5, 27];
const result = response.map((o, i) => ({ ...o, price: prices[i] }));
console.log(result);

Related

Create an array of objects with values from another object

I have an object looking like this
const item = {
id: 123,
type: 'book',
sections: [{
type: 'section',
id: '456',
index: 1,
lessons: [{
type: 'lesson',
id: 789,
index: 1
},
{
type: 'lesson',
id: 999,
index: 2
}
]
}, {
type: 'section',
index: 2,
id: 321,
lessons: [{
type: 'lesson',
id: 444,
index: 1
},
{
type: 'lesson',
id: 555,
index: 2
}
]
}]
}
It should be assumed that there are more objects in sections and lessons array. I want to create a new object like this
result = [{
section: 456,
lessons: [789, 999]
}, {
section: 321,
lessons: [444, 555]
}]
I tried this loop but this just pushes indexes and not lesson's ids
let obj = {};
let sectionWithLessons = [];
let lessons = []
for (const i in item.sections) {
obj = {
sectionId: item.sections[i].id,
lessonIds: item.sections[i].lessons.map((lesson) => {
return lessons.push(lesson.id)
}),
};
sectionWithLessons.push(obj);
}
console.log(sectionWithLessons);
How can i do this correctly and preferably with good performance in consideration?
I believe the best/shortest thing is to use the map function, like:
const result2 = item.sections.map(({id, lessons}) => ({
id,
lessons: lessons.map(({id: lessionId}) => lessionId)
}))
I would suggest using Array.map() to convert the item sections to the desired result.
We'd convert each section into an object with a section value and lessons array.
To create the lessons array, we again use Array.map() to map each lesson to a lesson id.
const item = { id: 123, type: 'book', sections: [{ type: 'section', id: '456', index: 1, lessons: [{ type: 'lesson', id: 789, index: 1 }, { type: 'lesson', id: 999, index: 2 } ] }, { type: 'section', index: 2, id: 321, lessons: [{ type: 'lesson', id: 444, index: 1 }, { type: 'lesson', id: 555, index: 2 } ] }] }
const result = item.sections.map(({ id, lessons }) => {
return ({ section: +id, lessons: lessons.map(({ id }) => id) })
});
console.log('Result:', result);
.as-console-wrapper { max-height: 100% !important; }

Remove multiple object from array Javascript [duplicate]

This question already has answers here:
Looping through array and removing items, without breaking for loop
(17 answers)
Closed 2 years ago.
I am trying to delete the all the objects with _id "bennyRawMaterial" from below details array nested in the object:
let recipeBasicRecipes = [{
_id:'12345',
name:'Macaron Shell',
details:[
{
name: 'Sugar',
_id: 'bennyRawMaterial',
type: 'solid',
}
,
{
name: 'Egg white',
_id: '5fef680ca43301322a3224e5',
type: 'solid'
}]
},
{
_id:'14512345',
name:'Macaron Shell',
details:[{
name: 'Castiors gar',
_id: 'bennyRawMaterial',
type: 'solid'
},
{
name: 'oil',
_id: 'bennyRawMaterial',
type: 'solid',
}
, {
name: 'food',
_id: 'bennyRawMaterial',
type: 'solid',
}]
}]
I am using following code to remove the objects, but it skips few of the objects.Please help with the implementation
recipeBasicRecipes.forEach(br => {
br.details.forEach((rm, index) => {
if (rm._id === 'bennyRawMaterial') {
br.details.splice(index, 1);
} else {
return true;
}
});
maintain a global ids array,
and go through the details array of each object
check the id exist in global ids array
let recipeBasicRecipes = [{
_id: '12345',
name: 'Macaron Shell',
details: [{
name: 'Sugar',
_id: 'bennyRawMaterial',
type: 'solid',
},
{
name: 'Egg white',
_id: '5fef680ca43301322a3224e5',
type: 'solid'
}
]
},
{
_id: '14512345',
name: 'Macaron Shell',
details: [{
name: 'Castiors gar',
_id: 'bennyRawMaterial',
type: 'solid'
},
{
name: 'oil',
_id: 'bennyRawMaterial',
type: 'solid',
}, {
name: 'food',
_id: 'bennyRawMaterial',
type: 'solid',
}
]
}
]
var uniqueIds = []; //global ids array
recipeBasicRecipes.forEach(el => {
let details = [];//unique details array
el.details.forEach((dt, i) => {
let id = dt._id;
if (!uniqueIds.includes(id)){ //check id exists in global ids array
uniqueIds.push(id);
details.push(dt); //copy unique details
}
});
el.details = details; //update details with unique details
});
console.log(recipeBasicRecipes)

Javascript How to get all values for a property from an Array of Objects?

Hello fellow Javascript developers, I hope you're all having a good day.
I'm trying to get all dynamically set values for certain properties of object elements from an array for my filter. For e.g.
var data = [
{id: 0, category: "RINGS", type: "CH"},
{id: 1, category: "NECKLACE", type: "CHE"},
{id: 2, category: "PENDANT", type: "CH"},
{id: 3, category: "BRACELET", type: "CH"},
{id: 4, category: "RINGS", type: "HBR"},
{id: 5, category: "PENDANT", type: "CHE"},
];
and exmaple array for how my data comes from the api. As you can see the two properties category & type that I know will always remain constant but their values may change based on user input data.
I want to set all available values for these two object props for my filter. How do I get all the values for a certain prop to get myself an array of values for a certain property which then I can assign to my Dropdown in React Native.
Result:
var category = [
{ name: "Rings", id: "RINGS"},
{ name: "Necklace", id: "NECKLACE"},
{ name: "Pendant", id: "PENDANT"},
{ name: "Bracelet", id: "BRACELET"},
]
and
var type = [
{ name: "CH", id: "CH" },
{ name: "CHE", id: "CHE" },
{ name: "HBR", id: "HBR" },
]
and then these two arrays are basically passed to the filter which will then be used to sort the data. I assume it's not too complex, but I'm a total beginner in javascript so bear with me. Thank You.
var data = [
{ id: 0, category: 'RINGS', type: 'CH' },
{ id: 1, category: 'NECKLACE', type: 'CHE' },
{ id: 2, category: 'PENDANT', type: 'CH' },
{ id: 3, category: 'BRACELET', type: 'CH' },
{ id: 4, category: 'RINGS', type: 'HBR' },
{ id: 5, category: 'PENDANT', type: 'CHE' }
];
const categories = [], types = [];
data.forEach((item) => {
if (!categories.includes(item.category)) {
categories.push(item.category);
}
if (!types.includes(item.type)) {
types.push(item.type);
}
});
const category = categories.map((item) => ({
name: item.toLowerCase(),
id: item
}));
const type = types.map((item) => ({ name: item, id: item }));
console.log(category);
console.log(type);
There are atleast 2 ways you can do this:
Using Array.includes. As #baymax mentioned above, you can filter through the array using includes.
Using Set in Javascript. Check out the code.
const data = [
{id: 0, category: "RINGS", type: "CH"},
{id: 1, category: "NECKLACE", type: "CHE"},
{id: 2, category: "PENDANT", type: "CH"},
{id: 3, category: "BRACELET", type: "CH"},
{id: 4, category: "RINGS", type: "HBR"},
{id: 5, category: "PENDANT", type: "CHE"},
];
// by includes
const uniqueCategories = [];
const uniqueTypes = []
data.forEach(entry => {
if (!uniqueCategories.includes(entry.category)){
uniqueCategories.push(entry.category)
}
if (!uniqueTypes.includes(entry.type)){
uniqueTypes.push(entry.type)
}
})
const categoriesMap = uniqueCategories.map(category => ({name: category.toLowerCase(), id: category}));
const typesMap = uniqueTypes.map(typeEntry => ({name: typeEntry, id: typeEntry}));
// by set
const categoriesSet = new Set()
const typesSet = new Set()
data.forEach(entry => {
categoriesSet.add(entry.category);
typesSet.add(entry.type);
});
const uniqueCategoriesFromSet = Array.from(categoriesSet).map(category => ({name: category.toLowerCase(), id: category}));
const uniqueTypesFromSet = Array.from(typesSet).map(typeEntry => ({name: typeEntry, id: typeEntry}));
console.log(uniqueCategoriesFromSet, uniqueTypesFromSet);
console.log(categoriesMap, typesMap)

How to compare objects using lodash regardless on their order

I am trying to compare two objects using lodash like below. The problem is that it always returns false. I think that the issue is that the objects have different order of keys and values. I however couldn't find a solution on how to compare it regardless on the order.
How to ignore the order and compare the two objects correctly?
var obj1 = {
event: 'pageInformation',
page: { type: 'event', category: 'sportsbook' },
username: 'anonymous',
pagePath: '/',
item: { name: 'Barcelona - Leganes', id: '123' },
contest: { name: '1.Španielsko', id: 'MSK70' },
category: { name: 'Futbal', id: 'MSK3' },
teams: [
{ id: 'barcelona', name: 'Barcelona' },
{ id: 'leganes', name: 'Leganes' }
]
}
var obj2 = {
event: 'pageInformation',
page: { type: 'event', category: 'sportsbook' },
username: 'anonymous',
pagePath: '/',
category: { id: 'MSK3', name: 'Futbal' },
contest: { name: '1.Španielsko', id: 'MSK70' },
item: { id: '123', name: 'Barcelona - Leganes' },
teams: [
{ name: 'Barcelona', id: 'barcelona' },
{ name: 'Leganes', id: 'leganes' }
]
}
function compareObjects(obj1, obj2){
return _.isMatch(obj1, obj2);
}
You can use the isEqual function which does a deep equal check (regardless of key order):
_.isEqual(obj1, obj2)
See more here: https://lodash.com/docs/2.4.2#isEqual

Remove attribute from JSON objects in a array [duplicate]

This question already has answers here:
How do I remove a property from a JavaScript object?
(37 answers)
Loop through an array in JavaScript
(46 answers)
Closed 4 years ago.
I have an array of json objects.
var user =[ { id: 1, name: 'linto', img: 'car' },
{ id: 2, name: 'shinto', img: 'ball' },
{ id: 3, name: 'hany', img: 'kite' } ]
From this is want to remove attribute img from all the elements of the array, so the output looks like this.
var user =[ { id: 1, name: 'linto' },
{ id: 2, name: 'shinto' },
{ id: 3, name: 'hany' } ]
Is there a way to do this in java script.
You can use .map() with Object Destructuring:
let data =[
{ id: 1, name: 'linto', img: 'car' },
{ id: 2, name: 'shinto', img: 'ball' },
{ id: 3, name: 'hany', img: 'kite' }
];
let result = data.map(({img, ...rest}) => rest);
console.log(result);
Array.prototype.map()
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
You can use map() in the following way:
var user =[ { id: 1, name: 'linto', img: 'car' },
{ id: 2, name: 'shinto', img: 'ball' },
{ id: 3, name: 'hany', img: 'kite' } ]
user = user.map(u => ({id: u.id, name: u.name}));
console.log(user);

Categories

Resources