I'm trying to render an array of objects using Map and so far I've only been able to render the first item to the browser.
I figured something's up with my .map function, but I don't know enough about React and JS to pinpoint the problem.
Here's my App.js file:
// import stuff is here
class App extends Component {
constructor(props) {
super(props);
this.state = {
items: []
};
this.componentWillMount = this.componentWillMount.bind(this);
}
componentWillMount() {
fetch('THE-JSON-URL-IS-HERE')
.then(res => res.json())
.then(data => {
this.setState({ items: data });
});
render() {
const { items } = this.state;
return (
<div className="App">
{ items.map((item, num) => {
return (
<div className="people">
<div className="elem">
<p key={num}>{item.elems}</p>
</div>
<p key={num}><strong>{item.name}</strong></p>
<p key={num}><small>{item.title}</small></p>
<div className="hidden">
<p key={num}><small>{item.email}</small></p>
<p key={num}><small><strong>Office: </strong>{item.office}</small></p>
</div>
{/* <p>{item.manager}</p> */}
</div>
);
})}
</div>
);
}
}
export default App;
And here's a sample of the JSON file:
[
{
"elems": "Pr",
"name": "Abby Langdale",
"title": "President",
"email": "alangdale0#hubpages.com",
"office": "Javanrud",
"manager": [
{
"elems": "Vp",
"name": "Johnnie Mouncey",
"title": "Vice President",
"email": "jmouncey0#cnet.com",
"office": "Canto",
"manager": [
{
"elems": "Vp",
"name": "Concordia Burgwyn",
"title": "VP Quality Control",
"email": "cburgwyn0#dyndns.org",
"office": "Zhoukou",
"manager": [
{
"elems": "En",
"name": "Prissie Sainsberry",
"title": "Web Developer IV",
"email": "psainsberry0#yellowbook.com",
"office": "Tugu",
"manager": null
},
etc. Abby's info is all that I've rendered.
Since you're nesting arrays and objects into your first array element, the length of items is 1 and the only element is the Abby element with the rest of the data nested inside of it. To map through all of the elements, items should look like this array:
[
{
"elems": "Pr",
"name": "Abby Langdale",
"title": "President",
"email": "alangdale0#hubpages.com",
"office": "Javanrud",
"manager": ""
},
{
"elems": "Vp",
"name": "Johnnie Mouncey",
"title": "Vice President",
"email": "jmouncey0#cnet.com",
"office": "Canto",
"manager": ""
},
{
"elems": "Vp",
"name": "Concordia Burgwyn",
"title": "VP Quality Control",
"email": "cburgwyn0#dyndns.org",
"office": "Zhoukou",
"manager": ""
},
{
"elems": "En",
"name": "Prissie Sainsberry",
"title": "Web Developer IV",
"email": "psainsberry0#yellowbook.com",
"office": "Tugu",
"manager": null
}
]
If you need to maintain the relationship of managers, you can add an id to each object and reference it from another object.
[
{
"elems": "Pr",
"name": "Abby Langdale",
"title": "President",
"email": "alangdale0#hubpages.com",
"office": "Javanrud",
"manager": "",
"id" : 1
},
{
"elems": "Vp",
"name": "Johnnie Mouncey",
"title": "Vice President",
"email": "jmouncey0#cnet.com",
"office": "Canto",
"manager": 1
},
...
]
You would need a filter helper function to do the correct lookup for a manager's name but it should work.
Try flattening the array first. You would need to know the maximum number of levels that the array will have. Once it's flattened, you can use your map function:
const flatItems = items.flat(3); // flatten up to 3 levels
items.map((item, num) => {
return ( <render your div> );
}
Related
const data = {
"games": [
{
"id": "828de9122149499183df39c6ae2dd3ab",
"developer_id": "885911",
"game_name": "Minecraft",
"first_release": "2011-18-11",
"website": "https://www.minecraft.net/en-us"
},
{
"id": "61ee6f196c58afc9c1f78831",
"developer_id": "810637",
"game_name": "Fortnite",
"first_release": "2017-21-07",
"website": "https://www.epicgames.com/fortnite/en-US/home"
},
],
"developers": [
{
"id": "885911",
"name": "Mojang Studios",
"country": "US",
"website": "http://www.mojang.com",
},
{
"id": "750245",
"name": "God of War",
"country": "SE",
"website": "https://sms.playstation.com",
},
] };
I have json data like this. I want to display data like if developer_id = 885911(from games array) then print id(from developers array) and if the both are same then I want to print the name.(Mojang studios) and so on like games website etc. How can I do that?
This sample code will show you the developer of each game, if it's found:
const data = {
"games": [
{
"id": "828de9122149499183df39c6ae2dd3ab",
"developer_id": "885911",
"game_name": "Minecraft",
"first_release": "2011-18-11",
"website": "https://www.minecraft.net/en-us"
},
{
"id": "61ee6f196c58afc9c1f78831",
"developer_id": "810637",
"game_name": "Fortnite",
"first_release": "2017-21-07",
"website": "https://www.epicgames.com/fortnite/en-US/home"
},
],
"developers": [
{
"id": "885911",
"name": "Mojang Studios",
"country": "US",
"website": "http://www.mojang.com",
},
{
"id": "750245",
"name": "God of War",
"country": "SE",
"website": "https://sms.playstation.com",
},
] };
const gameDevelopers = data.games.map(g => ({
game: g.game_name,
developer: data.developers.find(d => d.id === g.developer_id)?.name || "No matching developer found"
}));
console.log(gameDevelopers)
What did you exactly need? i don't understand . But you can get value Mojang Studios
console.log(data.developers[0].name)
If you need all developer id then you can use
console.log(data.developers.map(data=>{
console.log(data.id)
}))
If you need the id where name is Mojang Studios
console.log(data.developers.map(data=>{
if(data.name == "Mojang Studios"){
console.log(data.id)
}
}))
I'm currently trying to code an application with javascript. It pulls data from a database and the response I'm getting is something like that:
{
"values":[
{
"name": "Munich",
"location": "Germany",
"native_lang": "German",
},
{
"name": "London",
"location": "England",
"native_lang": "English",
},
{
"name": "Rome",
"location": "Italy",
"native_lang": "Italian",
}
]
}
But I need to have the JSON like that:
[
{
"name": "Munich",
"location": "Germany",
"native_lang": "German",
},
{
"name": "London",
"location": "England",
"native_lang": "English",
},
{
"name": "Rome",
"location": "Italy",
"native_lang": "Italian",
}
]
How can I delete the parent values object in my JSON?
SHORT ANSWER:
Just access the values property like a JavaScript object.
LONG ANSWER:
You didn't post the JavaScript code snippet so it's quite difficult to give you an appropriate answer.
Assuming you have the following code:
const jsonString = getDataFromTheDB()
const jsonObject = JSON.parse(jsonObject) // still has the "values" layer
const values = jsonObject.values // what you want, without the "values" layer
// BONUS: Just in case you want to convert the object back to a JSON string but without the "values" layer
const valuesJSON = JSON.stringify(values, undefined, 2)
Based on this post :
just do this (consider json the variable that contains your json):
var key = "values";
var results = json[key];
delete json[key];
json = results;
console.log(json) will output the following:
[
{
"name": "Munich",
"location": "Germany",
"native_lang": "German",
},
{
"name": "London",
"location": "England",
"native_lang": "English",
},
{
"name": "Rome",
"location": "Italy",
"native_lang": "Italian",
}
]
But you dont even have to do the last 2 steps of the code snippet above, you could also just directly use results variable and have the same output by console.log(results).
You could take the object and create a new variable with just the array.
var vals =
{
"values":[
{
"name": "Munich",
"location": "Germany",
"native_lang": "German",
},
{
"name": "London",
"location": "England",
"native_lang": "English",
},
{
"name": "Rome",
"location": "Italy",
"native_lang": "Italian",
}
]
}
var arr = vals.values;
console.log(arr);
I am a beginner in React trying to display one image at a time. Currently using this api https://salty-cove-08526.herokuapp.com/api/countries?format=json which sends 3 images at once. I am using axios to get the images and using map {this.state.countries.map(country => <img src={country.photo}/>)}
but this command in div img-wrapper displays all the 3 at once plz hlep
reactjs
class form extends Component{
constructor(props){
super(props);
this.state={
answer:'',
countries:[]
}
this.handleChange=this.handleChange.bind(this);
this.handleSubmit=this.handleSubmit.bind(this);
}
componentDidMount(){
axios.get('https://salty-cove-08526.herokuapp.com/api/countries?format=json')
.then(res=>{
this.setState({ countries:res.data});
})
}
}
render(){
return (
<div>
<section className="login">
<div className="loginContainer">
<div className="heading">
Guess the countries
</div>
<div className="img-wrapper">
{this.state.countries.map(country =>
<img src={country.photo}/>
)}
</div>
json
[
{
"id": 6,
"name": "canada",
"photo": "https://en.wikipedia.org/wiki/India#/media/File:Flag_of_India.svg",
"fact": "sdsds",
"capital": "sdsdsd",
"hint_1": "sdsd",
"hint_2": "sdsdsd"
},
{
"id": 2,
"name": "usa",
"photo": "https://en.wikipedia.org/wiki/India#/media/File:Flag_of_India.svg",
"fact": "ddc",
"capital": "new york",
"hint_1": "kuch bhi",
"hint_2": "kljn;kj"
},
{
"id": 3,
"name": "china",
"photo": "https://en.wikipedia.org/wiki/India#/media/File:Flag_of_India.svg",
"fact": "ddfdf",
"capital": "k k",
"hint_1": "jnjn",
"hint_2": "jknkjn"
}
]
You need to have something to determine which image you want to display. In the example below, I hold, in state, the index of the current image, and then only display the image at that index:
const images = [
{
"id": 6,
"name": "canada",
"photo": "https://en.wikipedia.org/wiki/India#/media/File:Flag_of_India.svg",
"fact": "sdsds",
"capital": "sdsdsd",
"hint_1": "sdsd",
"hint_2": "sdsdsd"
},
{
"id": 2,
"name": "usa",
"photo": "https://en.wikipedia.org/wiki/India#/media/File:Flag_of_India.svg",
"fact": "ddc",
"capital": "new york",
"hint_1": "kuch bhi",
"hint_2": "kljn;kj"
},
{
"id": 3,
"name": "china",
"photo": "https://en.wikipedia.org/wiki/India#/media/File:Flag_of_India.svg",
"fact": "ddfdf",
"capital": "k k",
"hint_1": "jnjn",
"hint_2": "jknkjn"
}
];
const PhotoDisplay = () => {
const [currentImageIndex, setCurrentImageIndex] = React.useState(0);
const handleNextClick = () => {
setCurrentImageIndex(currentImageIndex + 1);
};
const currentImage = images[currentImageIndex];
console.log(currentImage);
return <div>
<button onClick={handleNextClick}>Next Image</button>
<img src={currentImage.photo} />
</div>
}
ReactDOM.render(
<PhotoDisplay />,
document.getElementById('root')
)
<script crossorigin src="https://unpkg.com/react#17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#17/umd/react-dom.development.js"></script>
<div id="root"></div>
I am not sure how to form this question, but I will do my best.
I don't know how to remove object by _id from 'list:' part.
So, I have one array, and inside of that array I have list of objects,inside of these objects I have again array with objects, so I want to remove one object from that last array, how I can do that?
Cannot fix it for 2 days, I'm stucked!
Thanks!
[
{
"_id": "599a1344bf50847b0972a465",
"title": "British Virgin Islands BC",
"list": [],
"price": "1350"
},
{
"_id": "599a1322bf50847b0972a38e",
"title": "USA (Nevada) LLC",
"list": [
{
"_id": "599a1322bf50847b0972a384",
"title": "Nominee Member",
"service": "nominee-service",
"price": "300"
},
{
"_id": "599a1322bf50847b0972a385",
"title": "Nominee Manager & General Power of Attorney (Apostilled)",
"service": "nominee-service",
"price": "650"
},
{
"_id": "599a1322bf50847b0972a386",
"title": "Special Power of Attorney",
"service": "nominee-service",
"price": "290"
}
],
"price": "789"
},
{
"_id": "599a12fdbf50847b0972a2ad",
"title": "Cyprus LTD",
"list": [
{
"_id": "599a12fdbf50847b0972a2a5",
"title": "Nominee Shareholder",
"service": "nominee-service",
"price": "370"
},
{
"_id": "599a12fdbf50847b0972a2a6",
"title": "Nominee Director & General Power or Attorney (Apostilled)",
"service": "nominee-service",
"price": "720"
},
{
"_id": "599a12fdbf50847b0972a2ab",
"title": "Extra Rubber Stamp",
"service": "other-service",
"price": "40"
}
],
"price": "1290"
}
]
Using Vanilla JS:
function findAndRemove(data, id) {
data.forEach(function(obj) { // Loop through each object in outer array
obj.list = obj.list.filter(function(o) { // Filter out the object with unwanted id, in inner array
return o._id != id;
});
});
}
var data = [{
"_id": "599a1344bf50847b0972a465",
"title": "British Virgin Islands BC",
"list": [],
"price": "1350"
},
{
"_id": "599a1322bf50847b0972a38e",
"title": "USA (Nevada) LLC",
"list": [{
"_id": "599a1322bf50847b0972a384",
"title": "Nominee Member",
"service": "nominee-service",
"price": "300"
},
{
"_id": "599a1322bf50847b0972a385",
"title": "Nominee Manager & General Power of Attorney (Apostilled)",
"service": "nominee-service",
"price": "650"
},
{
"_id": "599a1322bf50847b0972a386",
"title": "Special Power of Attorney",
"service": "nominee-service",
"price": "290"
}
],
"price": "789"
},
{
"_id": "599a12fdbf50847b0972a2ad",
"title": "Cyprus LTD",
"list": [{
"_id": "599a12fdbf50847b0972a2a5",
"title": "Nominee Shareholder",
"service": "nominee-service",
"price": "370"
},
{
"_id": "599a12fdbf50847b0972a2a6",
"title": "Nominee Director & General Power or Attorney (Apostilled)",
"service": "nominee-service",
"price": "720"
},
{
"_id": "599a12fdbf50847b0972a2ab",
"title": "Extra Rubber Stamp",
"service": "other-service",
"price": "40"
}
],
"price": "1290"
}
];
// Empty almost all of list, except middle one
findAndRemove(data, "599a1322bf50847b0972a384");
findAndRemove(data, "599a1322bf50847b0972a386");
findAndRemove(data, "599a12fdbf50847b0972a2a5");
findAndRemove(data, "599a12fdbf50847b0972a2a6");
findAndRemove(data, "599a12fdbf50847b0972a2ab");
console.log(data);
Cleared everything except middle list, just for better visualization.
#Abhijit Kar your one is working perfectly, thanks mate!
How I can later splice this list?
When I was working with objects from first array, I did it like this :
var inventory = jsonArrayList;
for (var i = 0; i < inventory.length; i++) {
if (inventory[i]._id == deleteProductById) {
vm.items.splice(i, 1);
break;
}
}
It would be very helpful, thanks alot!
You can use Array.map and Array.filter to accomplish this. Detailed explanation in comments:
PS: This snippet uses ES6 arrow functions and spread operator
function removeById(arr, id) {
// Array.map iterates over each item in the array,
// and executes the given function on the item.
// It returns an array of all the items returned by the function.
return arr.map(obj => {
// Return the same object, if the list is empty / null / undefined
if (!obj.list || !obj.list.length) return obj;
// Get a new list, skipping the item with the spedified id
const newList = obj.list.filter(val => val._id !== id);
// map function returns the new object with the filtered list
return { ...obj, list: newList };
});
}
const oldArray = <YOUR_ORIGINAL_ARRAY>;
const newArray = removeById(arr, "599a12fdbf50847b0972a2a5");
Can someone please point out where I am making a mistake.
Its a very simple application that is meant to print out the "name" field in and array of Json objects, Which is done via the line :
{{ctrl.contact[0].results[0].name.first}} or
{{ctrl.contact[1].results[0].name.first}}
(which in itself seems very convoluted)
I cannot get it to print out the name of each Json block individually by loop and here is what i have tried :
<div ng-repeat="i in ctrl.contact">
<span>{{ctrl.contact[i].results[0].name.first}}</span>
</div>
Im confident after spending a few hours tweaking and editing that my angular set up (app, controller etc) is fine.
code snippet below :
<html ng-app="ContactAppApp">
<head>
<title>My Contact App</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.min.js"></script>
</head>
<body>
<div>
<div ng-controller="ContactAppController as ctrl">
<h1>{{ctrl.test}}</h1>
<div ng-repeat="i in ctrl.contact">
<span>{{ctrl.contact[0].results[0].name.first}}</span>
</div>
</div>
</div>
</body>
<script>
var app = angular.module("ContactAppApp", [])
app.controller("ContactAppController", ContactAppController);
function ContactAppController() {
this.test = "This text is generated by Angular";
this.contact = [
{
"results": [
{
"gender": "male",
"name": {
"title": "mr",
"first": "tony",
"last": "cruz"
},
"location": {
"street": "9813 north road",
"city": "edinburgh",
"state": "humberside",
"postcode": "E84 4YD"
}
}
]
},
{
"results": [
{
"gender": "male",
"name": {
"title": "mr",
"first": "Jack",
"last": "cruz"
},
"location": {
"street": "9813 north road",
"city": "edinburgh",
"state": "humberside",
"postcode": "E84 4YD"
}
}
]
}
]
}
</script>
</html>
Try the following:
<div ng-repeat="i in ctrl.contact">
<span>{{i.results[0].name.first}}</span>
</div>
I would set up your array a little differently. Try something like this:
this.contact = {
"results": [
{
"gender": "male",
"name": {
"title": "mr",
"first": "tony",
"last": "cruz"
},
"location": {
"street": "9813 north road",
"city": "edinburgh",
"state": "humberside",
"postcode": "E84 4YD"
}
},
{
"gender": "male",
"name": {
"title": "mr",
"first": "Jack",
"last": "cruz"
},
"location": {
"street": "9813 north road",
"city": "edinburgh",
"state": "humberside",
"postcode": "E84 4YD"
}
}
]
}
Then in your ng-repeat, try something like this:
<div ng-repeat="item in contact.results">
<span>{{item.name.first}} {{$index}}</span>
</div>
If you are trying to track the index of the item in array, use $index, not i.