I am trying to simplify the following state:
{
"name": "bulbasaur",
"picture": "https://raw",
"height": 7,
"weight": 69,
"types": [
{
"slot": 1,
"type": {
"name": "poison",
"url": "https://poke"
}
},
{
"slot": 2,
"type": {
"name": "grass",
"url": "https://poke"
}
}
]}
into something like this:
{
"name": "bulbasaur",
"picture": "https://raw",
"height": 7,
"weight": 69,
"types": [ "poison", "grass" ]
}
Also, I would like to mention that I have an array with 151 of these. Not every object contains two types; some only contain one.
I believe that is the reason most of what I have tried so far does not work. Thank you in advance for your help.
Try using map
let obj={ name: "bulbasaur", picture: "https://raw", height: 7, weight: 69, types : [{ slot: 1, type: { name: "poison", url:"https://poke" }}]};
obj.types=obj.types.map( Type => Type.type.name);
console.log(obj.types);
I think this is what you want, you will need to add this snippet in a loop for you dataset and have it pushed into a new array:
const Obj = {
"name": "bulbasaur",
"picture": "https://raw",
"height": 7,
"weight": 69,
"types" : [{
"slot": 1,
"type": {
"name": "poison",
"url":"https://poke"
}}, {
"slot": 2,
"type": {
"name": "grass",
"url":"https://poke"
}}
]};
const newObj = {
...Obj,
types: Obj.types.map((el) => el.type.name),
}
console.log(newObj)
I was able to resolve what I needed by using the logic provided by Ma'moun othman.
"name": "bulbasaur",
"picture": "https://raw",
"height": 7,
"weight": 69,
"types" : [{
"slot": 1,
"type": {
"name": "poison",
"url":"https://poke"
}}, {
"slot": 2,
"type": {
"name": "grass",
"url":"https://poke"
}}
]};
const newObj = {
...Obj,
types: Obj.types.map((el) => el.type.name),
}
console.log(newObj)
Related
I've got the following meetings object :
[
{
"id": 19,
"duration": 1.75,
"Employee": {
"name": "Jeanne",
}
},
{
"id": 20,
"duration": 1.00,
"Employee": {
"name": "Louis",
}
},
{
"id": 21,
"duration": 1.00,
"Employee": {
"name": "Jeanne",
}
}
]
I want to group it by Employee.name. Using reduce() here is what I come up with :
meetings.reduce(function (r, a) {
r[a.Employee.name] = r[a.Employee.name] || [];
r[a.Employee.name].push(a);
return r;
}
The resulting object is the following :
{
"Jeanne": [
{
"id": 19,
"duration": 1.75,
"Employee": {
"name": "Jeanne"
}
},
{
"id": 21,
"duration": 1.00,
"Employee": {
"name": "Jeanne"
}
}
],
"Louis": [
{
"id": 20,
"duration": 1.00,
"Employee": {
"name": "Louis"
}
}
]
}
If I try to map() or forEach() i cannot get the value of the element :
Array.from(thisMeeting).forEach(element => console.log(element));
return `undefined`;
Array.from-ming an Object will result in an empty array.
You'll have to iterate over the objects keys with Object.entries(thisMeeting).forEach… and grab the values inside that.
I want to rename some of my key's object but with a map it sounds quite difficult (I'm a newbie) here is my array :
"platforms": [
{
"id": 6,
"name": "PC (Microsoft Windows)"
},
{
"id": 11,
"name": "Xbox"
},
{
"id": 14,
"name": "Mac"
},
{
"id": 48,
"name": "PlayStation 4"
},
{
"id": 130,
"name": "Nintendo Switch"
}
],
And this is what i want it to be :
"platforms": [
{
"id": 6,
"name": "PC"
},
{
"id": 11,
"name": "Xbox"
},
{
"id": 14,
"name": "Mac"
},
{
"id": 48,
"name": "PS4"
},
{
"id": 130,
"name": "Switch"
}
],
And here is my code :
const renderedResults = results.map((result, index) => {
const platformSliced = result.platforms.slice(0,3);
return (
{platformSliced.map((platform) =>
<span className="main-game-card-platform">
{platform.name}.replace('PC (Windows Microsoft)', 'PC')
</span>
)}
);
});
It doesn't work maybe I should do a condition, but how can I write it ? Thank you
Create an object where the keys are the strings you want changed, and the values the strings that should replace the old string.
With .map() method, return a new object for each item, where the id is unchanged. The name property should look first in the new "rewrites" object if the value of name exists as a key in the object. If it does, then the value should be used, otherwise there is no rewrite and the old name should be used.
const rewrites = {
"PC (Microsoft Windows)": 'PC',
"PlayStation 4": 'PS4',
"Nintendo Switch": 'Switch'
};
const platforms = [
{
"id": 6,
"name": "PC (Microsoft Windows)"
},
{
"id": 11,
"name": "Xbox"
},
{
"id": 14,
"name": "Mac"
},
{
"id": 48,
"name": "PlayStation 4"
},
{
"id": 130,
"name": "Nintendo Switch"
}
];
const rewrittenPlatforms = platforms.map(({ id, name }) => ({
id,
name: rewrites[name] ?? name // Use rewritten name, if present, otherwise use old name.
}));
console.log(rewrittenPlatforms);
I have an object, which I need to turn into a list "grouped" by a child element. The current object is something like:
{
"results": [
{
"id": 14,
"name": "Productivity",
"category": {
"id": 4,
"name": "Work",
"color": "#fff",
"color2": "#999"
}
},
{
"id": 15,
"name": "Focus",
"category": {
"id": 4,
"name": "Work",
"color": "#fff",
"color2": "#999"
}
},
{
"id": 16,
"name": "Happiness",
"category": {
"id": 5,
"name": "Mood",
"color": "#fff",
"color2": "#999"
}
},
{
"id": 17,
"name": "Positivity",
"category": {
"id": 5,
"name": "Mood",
"color": "#fff",
"color2": "#999"
}
}
]
}
What I'm trying to accomplish is to sort and group results by the category.name key, ie:
[
{
"name": "Work",
"color": "#fff",
"color2": "#999",
"packs": [
{
"id": 14,
"name": "Productivity"
},
{
"id": 15,
"name": "Focus"
}
]
},
{
"name": "Mood",
"color": "#fff",
"color2": "#999",
"packs": [
{
"id": 16,
"name": "Happiness"
},
{
"id": 17,
"name": "Positivity"
}
]
}
]
And so on in such a way that I can loop over the result and build some sort of list.
I'm pretty sure there's a way to accomplish this with either map or reduce, but even though I've had some progress, I just can't seem to order the results in the way I need. (Pretty new to R/RN).
What I'm trying to accomplish in the long run is to be able to pass said info to a looped Component such as
<CategoryList
key={name}
title={name}
results={packs}
/>
Thanks in advance!
Use a Map with the category names as keys and new objects as values to group all the items by category.
When done grouping get the Map values and spread to array
const cats = data.results.reduce((a, {id, name, category:cat})=>{
const obj = a.get(cat.name) || {...cat, packs: []};
obj.packs.push({id, name});
return a.set(cat.name, obj);
}, new Map);
const res = [...cats.values()];
console.log(res)
.as-console-wrapper { max-height: 100%!important;}
<script>
const data={results:[{id:14,name:"Productivity",category:{id:4,name:"Work",color:"#fff",color2:"#999"}},{id:15,name:"Focus",category:{id:4,name:"Work",color:"#fff",color2:"#999"}},{id:16,name:"Happiness",category:{id:5,name:"Mood",color:"#fff",color2:"#999"}},{id:17,name:"Positivity",category:{id:5,name:"Mood",color:"#fff",color2:"#999"}}]};
</script>
var data = {
"results": [
{
"id": 14,
"name": "Productivity",
"category": {
"id": 4,
"name": "Work",
"color": "#fff",
"color2": "#999"
}
},
{
"id": 15,
"name": "Focus",
"category": {
"id": 4,
"name": "Work",
"color": "#fff",
"color2": "#999"
}
},
{
"id": 16,
"name": "Happiness",
"category": {
"id": 5,
"name": "Mood",
"color": "#fff",
"color2": "#999"
}
},
{
"id": 17,
"name": "Positivity",
"category": {
"id": 5,
"name": "Mood",
"color": "#fff",
"color2": "#999"
}
}
]
};
var processedData = [];
data['results'].forEach(result => {
var pack = {
'id': result['id'],
'name': result['name']
};
var category = processedData.find(element => element['name'] === result['category']['name']);
if (category) {
category['packs'].push(pack);
} else {
category = {
'name': result['category']['name'],
'color': result['category']['color'],
'color2': result['category']['color2'],
'packs': [pack]
};
processedData.push(category);
}
});
console.log(processedData);
I am trying to access keys and arrays in my json structure with Array.map() but I'm missing something.
Here's my JSON:
{
"payload": [
{
"id": 1,
"name": "Atta",
"brands": [
{
"id": 118,
"name": "Wheatola",
"subProducts": [
{
"id": 858,
"name": "Chakki Aata",
"minPrice": 52,
"maxPrice": 56
},
{
"id": 2,
"name": "Chakki Atta",
"minPrice": 222,
"maxPrice": 236
}
]
}
]
},
{
"id": 16,
"name": "Rice (Branded)",
"brands": [
{
"id": 25,
"name": "CookStar",
"subProducts": [
{
"id": 1163,
"name": "Best Basmati",
"creditDays": 0,
"minPrice": 5600,
"maxPrice": 5600
},
{
"id": 863,
"name": "Extra Long Grain Basmati",
"creditDays": 0,
"minPrice": 7800,
"maxPrice": 7800
}
]
}
]
}
]
}
I want to access payload.name, payload.brands.name(s), payloads.brands.subproducts.name(s) with Array.map() and render the values in components. How do I access nested json like using map()?
Expected output is:
Atta, Wheatola, Chakki Aata
Atta, Wheatola, Chakki Aata
Rice (Branded), Cookstar, Best Basmati
Rice (Branded), Cookstar, Extra Long Grain Basmati
You need to nest Array.map()
var data = {
"payload": [
{
"id": 1,
"name": "Atta",
"brands": [
{
"id": 118,
"name": "Wheatola",
"subProducts": [
{
"id": 858,
"name": "Chakki Aata",
"minPrice": 52,
"maxPrice": 56
},
{
"id": 2,
"name": "Chakki Atta",
"minPrice": 222,
"maxPrice": 236
}
]
}
]
},
{
"id": 16,
"name": "Rice (Branded)",
"brands": [
{
"id": 25,
"name": "CookStar",
"subProducts": [
{
"id": 1163,
"name": "Best Basmati",
"creditDays": 0,
"minPrice": 5600,
"maxPrice": 5600
},
{
"id": 863,
"name": "Extra Long Grain Basmati",
"creditDays": 0,
"minPrice": 7800,
"maxPrice": 7800
}
]
}
]
}
]
}
const renderData = data.payload.map((payload) => {
return payload.brands.map(brand =>{
return brand.subProducts.map(subProduct => {
return `${payload.name}, ${brand.name}, ${subProduct.name}`
}).join("\n")
}).join("\n")
}).join("\n")
console.log(renderData);
Here might be a working example (without styling or anything):
render() {
return (
<div>
{
json.payload.map(j =>
<div>
{j.name}
{j.brands.map(b =>
<div>
{b.name}
{b.subProducts.map(s =>
<div>
{s.name}
</div>)
}
</div>
)}
</div>
)
}
</div>
);
}
You probably need to style it, or combine it with a table and columns, because it just renders the values now.
You can also use forEach since you'll have to nest map calls but you expect a flat array (?) in the end :
var json = {
"payload": [{
"id": 1,
"name": "Atta",
"brands": [{
"id": 118,
"name": "Wheatola",
"subProducts": [{
"id": 858,
"name": "Chakki Aata",
"minPrice": 52,
"maxPrice": 56
},
{
"id": 2,
"name": "Chakki Atta",
"minPrice": 222,
"maxPrice": 236
}
]
}]
},
{
"id": 16,
"name": "Rice (Branded)",
"brands": [{
"id": 25,
"name": "CookStar",
"subProducts": [{
"id": 1163,
"name": "Best Basmati",
"creditDays": 0,
"minPrice": 5600,
"maxPrice": 5600
},
{
"id": 863,
"name": "Extra Long Grain Basmati",
"creditDays": 0,
"minPrice": 7800,
"maxPrice": 7800
}
]
}]
}
]
}
var result = [];
json.payload.forEach(product => {
product.brands.forEach(brand => {
brand.subProducts.forEach(subProduct => {
result.push([product.name, brand.name, subProduct.name].join(', '));
});
});
});
console.log(result);
I came across the following scenario
var obj1= [
{
"id": 97,
"name": "Sample1",
"classId": 751,
"gradeId": 1,
"studentId": 1
},
{
"id": 98,
"name": "Sample2",
"classId": 751,
"gradeId": 1,
"studentId": 2
},
{
"id": 97,
"name": "Sample1",
"classId": 751,
"gradeId": 2,
"studentId": 3
},
{
"id": 98,
"name": "Sample2",
"classId": 751,
"gradeId": 2,
"studentId": 4
}
]
Now ,If the id's are same,I need to combine the identical object values in the following form
var obj2=[
{
"id": 97,
"name": "Sample1",
"classId": 751,
"rating":[
{
"gradeId": 1,
"studentId": 1
}
{
"gradeId": 2,
"studentId": 3
}
]
},
{
"id": 98,
"name": "Sample2",
"classId": 751,
"rating":[
{
"gradeId": 1,
"studentId": 2
}
{
"gradeId": 2,
"studentId": 4
}
]
}
]
I am looping through all the objects and ifnthe id's are same I am creating a new object with the combined values,which i feel a little bit elaborated
Can i achieve this through underscore js in a more abstract way?
_.groupBy will do what you want, then use pick/omit to map the groups to the nested objects as you want them:
var obj2 = _.map(_.groupBy(obj1, "id"), function(group) {
var o = _.omit(group[0], "gradeId", "studentId");
o.rating = _.map(group, function(s) {
return _.pick(s, "gradeId", "studentId");
});
return o;
});