How to get the object and display in html javascript - javascript

I would like to know how to iterate over object array in javascript.
I have an array sample in which property options should be displayed in lit-HTML for every object
var sample = [{
"trans": [{
"id": "trans",
"fee": 20,
"options": ["credit", "debit"]
}],
"insta": [{
"id": "insta",
"fee": 30,
"options": ["bank", "credit"]
}]
}]
render(){
sample.map((r)=>{
<select>
r.options.map((e)=>
return html`
<option>${e.options}</option>
`
)
</select>
}
}

I think what you need here is something like this (you are missing the return in the render function):
var sample=[{
"trans":[{
"id": "trans",
"fee": 20,
"options": ["credit", "debit"]
}],
"insta":[{
"id": "insta",
"fee": 30,
"options":["bank", "credit"]
}]
}]
render(){
return sample.map((r)=>{
<select>
r.options.map((e)=>
return html`
<option>${e.options}</option>
`
)
</select>
}
}

you are applying Array.map to r.options, so each element is already a single option, so you need to simply invoke
r.options.map( e => html`<option>${e}</option>`)

e is already the value of the options array element, you don't need to use e.options. So it should just be
<option>${e}</option>
You also need to loop over r.trans.options and r.insta.options.
render(){
sample.map((r)=>{
<select>
r.trans.options.map((e)=>
return html`
<option>${e}</option>
`
)
</select>
<select>
r.insta.options.map((e)=>
return html`
<option>${e}</option>
`
)
</select>
}
}

Related

Display div element if specific value exists in JSON object in JavaScript Vue Js

I need to display Div element if specific value exists on JSON object and I have tried using array I could success but I don't know how to do in JSON object. Simply I need to display div if value called "Channel" exists on JSON object.
Below code that I tried but it didn't work
activationTypes: [
{
"activationTypeId": 1,
"name": "SMS"
},
{
"activationTypeId": 2,
"name": "WEB"
},
{
"activationTypeId": 3,
"name": "Channel"
}
]
<div v-show="Object.values(activationTypes).includes('Channel')">
<p>test<test>
</div>
Simple Check:
activationTypes.some( item => item['name'] === 'Channel' );
Reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
Use .find to search for the element by name:
new Vue({
el:"#app",
data(){
return{
activationTypes: [
{
"activationTypeId": 1,
"name": "SMS"
},
{
"activationTypeId": 2,
"name": "WEB"
},
{
"activationTypeId": 3,
"name": "Channel"
}
]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-show="activationTypes.find(e=>e.name=='Channel')">
<p>test</p>
</div>
</div>

React - wrap multiple elements in parent node

I have the following array of words that compose some sentences:
let words = [
{
"start_time": "2.54",
"end_time": "3.28",
"alternatives": [
{
"confidence": "1.0",
"content": "Hello",
"__typename": "Alternative"
}
],
"type": "pronunciation",
"__typename": "TranscriptItems"
},
{
"start_time": null,
"end_time": null,
"alternatives": [
{
"confidence": "0.0",
"content": ".",
"__typename": "Alternative"
}
],
"type": "punctuation",
"__typename": "TranscriptItems"
},
{
"start_time": "3.29",
"end_time": "3.52",
"alternatives": [
{
"confidence": "1.0",
"content": "This",
"__typename": "Alternative"
}
],
"type": "pronunciation",
"__typename": "TranscriptItems"
}
]
Also i have this variable that contain an array of snippets selected from the words above:
const snippets = [{ start: 2.54, end: 4.00, id: 12, snippetTitle: "This is the title" }];
Right now I am showing the words by doing a simple .map and returning <span>s for every word.
What I am trying to accomplish is the following: if the span i am currently on is between a snippet from snippets variable, wrap it in another div/component so i can highlight it.
So instead of <span>Hello</span>.<span>This</span> i would be able to wrap both spans in a new wrapper component or div like <Highlight><span>Hello</span>.<span>This</span></Highlight>
You can do something like this using the reduce function:
export default myComponent = () => {
let cache = [];
return (
<>
{myArray.reduce((accumulator, currentValue) => {
if(!isInSnippets(currentValue)){
if(cache.length > 0){ // return the cached value for highlight
accumulator.push( (<Highlight>
{cache.map((elt, i) => <span key={i}>{elt}</span>)
</Highlight>));
cache = [];
}
accumulator.push(<span>{currentValue}</span>);
}
else cache.push(currentValue);
return accumulator;
}}
</>
)
}
The accumulator will contain an array of jsx elements. The regular elements will be contained in spans, while the Highlighted elements will be contained all together within a Highlight component.
We store the Highlighted elements in a cache variable. When we face a "regular" element, we check if there is something in the cache. If there is, we put them all in a highlight element, and add it to the cache. Then we add the "current" regular value.

React cannot map through prop array

I fetch an api on componentDIdMount() then store the json to a state then I pass that state as a prop, I have no problem showing the data except on arrays.
<Component details={this.state.details} />
json:
{
"adult": false,
"backdrop_path": "/qonBhlm0UjuKX2sH7e73pnG0454.jpg",
"belongs_to_collection": null,
"budget": 90000000,
"genres": [
{
"id": 28,
"name": "Action"
},
{
"id": 878,
"name": "Science Fiction"
},
{
"id": 35,
"name": "Comedy"
},
{
"id": 10751,
"name": "Family"
}
]
}
then I try to map the genres:
<div className={style.genre}>
{details.genres.map(g => (
<span key={g.id}>{g.name}</span>
))}
</div>
But then I get Cannot read property 'map' of undefined, I don't know why this is happening because I'm able to do details.budget
It's trying to read data before you get the result from api.
so write the map function as
{details&&details.genres&&details.genres.map(g => (
<span key={g.id}>{g.name}</span>
))}
In react Initially when component is mounted, render() function is called and then componenentDidMount() is called in which you fetch data. So Initially details is empty. So you need to write the condition.

React element - array objects only returning first item?

I am trying to retrieve item values from an object containing several items. The object is an array object. I am puzzled by only being able to retrive the first item and its values in each array instead of all items. Can anybody tell me what I am missing here.
The array object example:
{ "ITEM 1": [
{
"id": 123,
"name": "item1a"
},
{
"id": 234,
"name": "item1b"
},
{
"id": 345,
"name": "item1c"
}
],
"ITEM 2": [
{
"id": 456,
"name": "item2a"
},
{
"id": 567,
"name": "item2b"
},
{
"id": 678,
"name": "item2c"
}],
}
I have data within the new element and on debugging see that loop flows correctly but for some reason only the first item is rendered.
My code that is wrapped in an html element is as follows:
{ Object.keys(this.props.data).map(function (key) {
var list = component.props.data[key];
for (i = 0; i < facetParent.length; i++) {
var item = list[i];
return (
<CheckBox
key={item.id}
data={item}
name={item.name} />
)
}}, this)}
Any suggestions are much appreciated.
The return function immediately terminates the function execution. That is why you only get the first item. Depending on what version of react you use, you should create 2 arrays and join them before rendering

accessing multidimensional array with React js

I am working with a json api and I'm able to access the api and list out the first array with the map method but can't access anything beyond that.
{
"client_id": 1,
"client_name": "Moen, Hickle and Stehr",
"products": [ {
"product_id": 1,
"product_name": "Ergonomic Cotton Keyboard",
"product_asin": "cfq35yoyh64i",
"product_image_url": "https://unsplash.it/310/676",
"keywords": [ {
"keyword_id": 1,
"keyword_name": "nam",
"keyword_country": "LV",
"ranks": [ {
"rank_id": 1,
"rank_position": 214,
"rank_page": 2,
"rank_date": "2016-08-16"
}, {
"rank_id": 2,
"rank_position": 82,
"rank_page": 3,
"rank_date": "2016-11-12"
} ]
} ]
}]
}
How do I access the keywords and rank arrays? Is there a way to use the map method to nest in the prods function and output the keyword and ranking info?
var Product = React.createClass({
render: function() {
var prods = this.props.products.map(function(item, index){
return(
<ul key={index}>
<li>{item.product_name} </li>
<li>{item.product_image_url}</li>
</ul>
)
});
return (
<div className="col-sm-12 compBlock">
<div className="col-sm-6">
<h3>{this.props.name}</h3>
{prods}
</div>
</div>
)
}
I think something like this snippet should work.
I am using the map method within the high-level map call and assigning the results to a variable that I include in the high-level's return object
const props = {
"client_id": 1,
"client_name": "Moen, Hickle and Stehr",
"products": [ {
"product_id": 1,
"product_name": "Ergonomic Cotton Keyboard",
"product_asin": "cfq35yoyh64i",
"product_image_url": "https://unsplash.it/310/676",
"keywords": [ {
"keyword_id": 1,
"keyword_name": "nam",
"keyword_country": "LV",
"ranks": [ {
"rank_id": 1,
"rank_position": 214,
"rank_page": 2,
"rank_date": "2016-08-16"
}, {
"rank_id": 2,
"rank_position": 82,
"rank_page": 3,
"rank_date": "2016-11-12"
} ]
} ]
}]
};
const prods = props.products.map((item, index) => {
const keywords = item.keywords.map(cur => {
return (
<span>
<li>{cur.keyword_name}</li>
<li>{cur.keyword_country}</li>
</span>
);
});
return(
<ul key={index}>
<li>{item.product_name}</li>
<li>{item.product_image_url}</li>
{keywords}
</ul>
);
});
console.log(prods);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
"Is there a way to use the map method to nest in the prods function and output the keyword and ranking info?"
Answer: Yes.
You know that there is a property keywords that is an array of objects much like this.props.products.
To access, it you can use dot notation as you have with other properties within your existing .map() call.
To access, a property of an object on the array keywords, you can call .map() on it and access the property you want again with for notation:
var prods = this.props.products.map(function(item, index){
// You already are referencing these:
item.product_name
item.product_image_url
// To access keywords:
item.keywords ( the keywords array )
// Nested map on keywords can be called here also:
item.keywords.map(function(current,index){
// You can now access .ranks:
current.ranks
});
});

Categories

Resources