ReactJS : RestAPI JSON response : How to Parse - javascript

As a ReactJS newbie, I tried to parse RestfulAPI JSON reponse, But, I couldn't retrieve all elements. While trying to access text.subjects.code and text.subjects.description, it returns null. However, I could successfully access text.id and text.name.
JSON response is given below.
[
{
"id":95822,
"name":"Alex",
"subjects":[
{
"code": "101",
"description": "Course 101"
}
]
}
]
Kindly advise.

You can do iteration in many ways and few ways which I always prefer using .forEach and .map
If you need new array then go with .map. Because map returns a new array
const dataArray = text.subjects.map(subject => {
let obj = {};
obj.code = subject.code;
obj.description = subject.description;
return obj;
});
//dataArray will contain all the objects
There is also a Different way of doing map
const dataArray = text.subjects.map(subject => (
let obj = {};
obj.code = subject.code;
obj.description = subject.description;
return obj;
);
Or if you want to just iterate the data then use .forEach. forEach doesn’t return an array
let array = [];
text.subjects.forEach(subject => (
let obj = {};
obj.code = subject.code;
obj.description = subject.description;
array.push(obj);
));

if You check subjects is an array and you are not getting value from it, try
text.subjects[0].code

Because subjects is an array and you should map subject like the following:
text.subjects.map((subject) => {
console.log(subject.code, subject.description);
})
or directly get the index that you to want like the following:
text.subjects[0].code

Related

How to convert json object keys into different arrays removing the duplicate

I'm having the JSON like this i need to group this JSON with all the keys in JSON object and value should in array (excluding duplicates).
var people = [
{sex:"Male", name:"Jeff"},
{sex:"Female", name:"Megan"},
{sex:"Male", name:"Taylor"},
{sex:"Female", name:"Madison"}
];
My output should be like
{"sex":["Male","Female"],"name":["Jeff","Megan","Taylor","Madison"]}
how we can able to achieve this
function getValues(array) {
var result = {};
array.forEach(obj => {
Object.keys(obj).forEach(key => {
if(!Array.isArray(result[key]))
result[key] = [];
result[key].push(obj[key]);
})
})
return result;
}
You could use the Array.reduce() method to transform your array into a single object:
var people = [
{sex:"Male", name:"Jeff"},
{sex:"Female", name:"Megan"},
{sex:"Male", name:"Taylor"},
{sex:"Female", name:"Madison"}
];
const transformed = people.reduce((acc, e) => {
Object.keys(e).forEach((k) => {
if (!acc[k]) acc[k] = [];
if (!acc[k].includes(e[k])) acc[k].push(e[k]);
});
return acc;
}, {});
console.log(transformed);
If for one of the object keys (sex or name in this case) a value array does not exist, it is created. Before a value is pushed into any of the value arrays, it is verified that it is not already present in that array.

get only the unique value of an array

I am new to javascript and I tried like using distinct but its not what im looking for
example array:
let arr = [ {key:"1",value:"dog"},
{key:"1",value:"dog"},
{key:"2",value:"cat"},
{key:"3",value:"bird"},
{key:"3",value:"bird"},
]
on the code I try is its just removing the duplicate like
[ {key:"1",value:"dog"},
{key:"2",value:"cat"},
{key:"3",value:"bird"}, ]
how can I get only the
[ {key:"2",value:"cat"} ]
what I mean is only the one who have no duplicate and its removing those array that have the exact same?
You can map your objects to stringified versions of your objects so you can then use .indexOf and .lastIndexOf() to compare if the object found appears in different locations in your array, if the last and first index appear in the same location then it can be said that they're the same object (ie: a duplicate doesn't exist) and can be kept in your resulting array like so:
const arr = [{key:"1",value:"dog"},{key:"1",value:"dog"},{key:"2",value:"cat"},{key:"3",value:"bird"},{key:"3",value:"bird"}];
const searchable = arr.map(JSON.stringify);
const res = arr.filter((obj, i) => {
const str = JSON.stringify(obj);
return searchable.indexOf(str) === searchable.lastIndexOf(str);
});
console.log(res);
If you can use Javascript libraries such as underscore or lodash, I recommend having a look at _.xorBy function in their libraries. From lodash:
_.xorBy([arrays], [iteratee=_.identity])
Basically, you pass in the array that in here is an object literal and you pass in the attribute that you want to all occurrences of remove duplicates with in the original data array, like this:
var data = [ {key:"1",value:"dog"}
, {key:"1",value:"dog"}
, {key:"2",value:"cat"}
, {key:"3",value:"bird"}
, {key:"3",value:"bird"}
];
var non_duplidated_data = _.xorBy(data, 'key');
Source - https://lodash.com/docs/4.17.14#xorBy
You can use reduce and Map
let arr = [{key:"1",value:"dog"},{key:"1",value:"dog"},{key:"2",value:"cat"},{key:"3",value:"bird"},{key:"3",value:"bird"}]
let mapper = arr.reduce( (op,inp) => {
let {key} = inp
op.set(key, op.get(key) || {value: inp, count:0})
op.get(key).count++
return op
},new Map())
let final = [...mapper.values()].reduce((op,{value,count}) => {
if(count === 1){
op.push(value)
}
return op
},[])
console.log(final)
Using the "find" method, you will get exactly what you are looking for "{key:"2",value:"cat"}".
arr.find((item, index) => {
const foundDup = arr.find((s, sIndex) => sIndex !== index && s.key === item.key);
return !foundDup;
});
If you don't mind using a library, I strongly suggest using the "ramda" library.
const arr = [ {key:"1",value:"dog"}
, {key:"1",value:"dog"}
, {key:"2",value:"cat"}
, {key:"3",value:"bird"}
, {key:"3",value:"bird"}
];
const result = R.uniq(arr);
result will be:
[{"key": "1", "value": "dog"}, {"key": "2", "value": "cat"}, {"key": "3", "value": "bird"}]
you can use "lodash" or other similar libraries too.

Java script filter on array of objects and push result's one element to another array

I have a array called data inside that array I have objects.
An object structure is like this
{
id:1,
especial_id:34,
restaurant_item:{id:1,restaurant:{res_name:'KFC'}}
}
I want to pass a res_name eg:- KFC
I want an output as a array which consists all the especial_ids
like this
myarr = [12,23,23]
I could do something like this for that. But I want to know what is more elegant way to do this.
const data = [
{id:1,especial_id:6,restaurant_items:{id:5,res_name:'McDonalds'}},
{id:1,especial_id:8,restaurant_items:{id:5,res_name:'Kfc'}},
{id:1,especial_id:6,restaurant_items:{id:5,res_name:'Sunmeal'}},
{id:1,especial_id:6,restaurant_items:{id:5,res_name:'Kfc'}},
];
let temp = data.filter(element => element.restaurant_items.res_name == 'kfc')
let myArr = [];
temp.forEach(element=> myArr.push(element.especial_id));
console.log(myArr)//[8,6]
You can try this. It uses "Array.filter" and "Array.map"
var data = [
{id:1,especial_id:6,restaurant_items:{id:5,res_name:'McDonalds'}},
{id:1,especial_id:8,restaurant_items:{id:5,res_name:'Kfc'}},
{id:1,especial_id:6,restaurant_items:{id:5,res_name:'Sunmeal'}},
{id:1,especial_id:6,restaurant_items:{id:5,res_name:'Kfc'}},
];
function getEspecialIdsByName(name) {
return data.filter(d => d.restaurant_items.res_name.toLowerCase() == name.toLowerCase())
.map(d => d.especial_id)
}
console.log(getEspecialIdsByName('Kfc'))
console.log(getEspecialIdsByName('Sunmeal'))
You can reduce to push elements which pass the test to the accumulator array in a single iteration over the input:
const data = [
{id:1,especial_id:6,restaurant_items:{id:5,res_name:'McDonalds'}},
{id:1,especial_id:8,restaurant_items:{id:5,res_name:'Kfc'}},
{id:1,especial_id:6,restaurant_items:{id:5,res_name:'Sunmeal'}},
{id:1,especial_id:6,restaurant_items:{id:5,res_name:'Kfc'}},
];
console.log(
data.reduce((a, { especial_id, restaurant_items: { res_name }}) => {
if (res_name === 'Kfc') a.push(especial_id)
return a;
}, [])
);
Use Array.reduce
const data = [{id:1,especial_id:6,restaurant_items:{id:5,res_name:'McDonalds'}},{id:1,especial_id:8,restaurant_items:{id:5,res_name:'Kfc'}},{id:1,especial_id:6,restaurant_items:{id:5,res_name:'Sunmeal'}},{id:1,especial_id:6,restaurant_items:{id:5,res_name:'Kfc'}}];
let result = data.reduce((a,c) => {
if(c.restaurant_items.res_name === 'Kfc') a.push(c.especial_id);
return a;
},[]);
console.log(result);

Issue in removing object using Lodash _remove

I am having an Object:
ids = [ "-LIof_e0hPtXKtkc4Uh9", "-LIjBcGO7m7VQ-B3pfYt" ]
If I Iterate using .map function of lodash
_.map(ids, (userID, key) => {
console.log('Lopping userId',userID);
})
it gives me value of each id.
Now when I am trying to remove it using _remove it is not working as expected.
_.remove(ids, (value, key, obj) => value == idToBeRemoved);
Still there is no difference in ids Object.
I am really new to angular4 and using lodash for the first time.
I just wanted to remove a value from ids object and get the remaining object.
Print of console.
I am using firebase and trying to delete data after retrieving it from firebase :
deleteTransactWith(transactWithKey,transactWithUser) {
let currentUser = this._authService.getLoggedInUser();
console.log(transactWithUser.groups)
console.log(Object.keys(transactWithUser.groups).length)
console.log('key To remove',transactWithKey)
for (var key in transactWithUser.groups) {
if (transactWithUser.groups.hasOwnProperty(key)) {
let group = this.firebase.object(`/url/${currentUser.$key}/${key}`);
group.snapshotChanges().take(1).subscribe((groupData: any) => {
groupData = groupData.payload.toJSON();
//console.log('not removed',groupData.userIds)
console.log('key',transactWithKey)
_.remove(groupData.userIds, (value) => value == transactWithKey);
//_.pull(groupData.userIds, transactWithKey);
console.log('removed',groupData.userIds)
});
}
}
You want _filter instead
const ids = [ "-LIof_e0hPtXKtkc4Uh9", "-LIjBcGO7m7VQ-B3pfYt" ]
const idToBeRemoved = "-LIof_e0hPtXKtkc4Uh9"
const filteredIds = _.filter(ids, function(id) { return id !== idToBeRemoved})
console.log(filteredIds)
You can simply use lodash _.pull
const _ = require("lodash");
const ids = [ "-LIof_e0hPtXKtkc4Uh9", "-LIjBcGO7m7VQ-B3pfYt" ]
const result = _.pull(ids, "-LIjBcGO7m7VQ-B3pfYt" )
console.log(filteredIds)
First find the index of what you are removed item and next pull out from it by _.pullAt(lodash)
let getIndex= _.findIndex(this.images, function(o) { return o.name == img.name; });
let removedImage = _.pullAt(this.images, getIndex) ;

reactJS adding a object array to and object within an object array

I got a response from a REST call, which returns and array with objects
response.data.steps
For example it looks like this
Now I need to add to each Child of this array an new Object Array.
What could be a smart solution for this problem?
Thanks.
In order to add a new array property to each item, you can simply do:
const steps = response.data.steps.map(step => ({
...step,
newObjectArray: [],
}))
you can usee Array.prototype.map() to do so
let result = response.data.steps.map(element => {
let ret = [element];
return ret;
});
let arr = [{a:1}, {a:2}, {a:3}];
arr = arr.map(element => {
let ret = [element];
return ret;
});
console.log(arr);

Categories

Resources