hope you guys have a great day!
I'am learning Flutter, and now i got some obstacle to display data from array object, so i have the array object look like this:
// i saved this array object to listLorem var
listLorem = [
{
"ids": 12,
"someText": "Lorem Ipsum #12",
},
{
"ids": 11,
"someText": "Lorem Ipsum #11",
},
]
and then, i want to display it on my DropDownItems, somethins looks like this:
items: [
DropdownMenuItem(
child: Text("Choose One"),
value: "",
),
listLorem.map((items) => DropdownMenuItem(
child: Text(items.someText),
value: items.ids,
)),
],
====== EDIT =========
and this is my console said (with all red)
listLorem((items) => DropdownMenuItem(
^
: Error: The argument type 'List<Object>' can't be assigned to the parameter type 'List<DropdownMenuItem<String>>?'.
register.dart:569
- 'List' is from 'dart:core'.
- 'Object' is from 'dart:core'.
- 'DropdownMenuItem' is from 'package:flutter/src/material/dropdown.dart' ('../../../../../flutter/packages/flutter/lib/src/material/dropdown.dart').
i've tried others method, but i still didn't know how to do it right, i got "redline" all over the place :(
Your code should be as following
items: [
DropdownMenuItem(
child: Text("Choose One"),
value: "",
),
...listLorem.map((items) => DropdownMenuItem(
child: Text(items.someText),
value: items.ids,
)),//...(triple dots) is represents list is getting appended
],
Or
items: [
DropdownMenuItem(
child: Text("Choose One"),
value: 0,
),
...listLorem.map((items) => DropdownMenuItem(
child: Text(items.someText),
value: items.ids,
)),//...(triple dots) is represents list is getting appended
],```
Related
I'm working with a tree nodes and I want to create a function to find an item by its ID.
What is the best and optimal solution to get it?
I think it will be a recursive function, but I'm not sure and I want a help please to choose what I will use to resolve this issue :)
This is my example:
const treeData = [
{
title: 'parent 1',
key: 11,
children: [
{
title: 'parent 1-0',
key: 12,
children: [
{
title: 'leaf',
key: 13,
children: [
{
title: 'leaf111',
key: 14,
},
{
title: 'leaf',
key: 15,
},
],
},
{
title: 'leaf666',
key:88,
},
],
},
{
title: 'parent 1-1',
key: 55,
children: [
{
title: (
<span
style={{
color: '#1890ff',
}}
>
sss
</span>
),
key: '0-0-1-0',
},
],
},
],
},
];
Input : 14
Output : {title: 'leaf111',key: 14},
We can create a rerusive function that:
Loops though each object in the array and
Returns the object if id matches
Calls itself with the objects children
const treeData = [{title: 'parent 1', key: 11, children: [{title: 'parent 1-0', key: 12, children: [{title: 'leaf', key: 13, children: [{title: 'leaf111', key: 14, }, {title: 'leaf', key: 15, }, ], }, {title: 'leaf666', key:88, }, ], }, {title: 'parent 1-1', key: 55, children: [{title: '(<span style={{color: \'#1890ff\', }} > sss </span> )', key: '0-0-1-0', }, ], }, ], }, ];
const findById = (e, id) => {
for (let o of e) {
return (o.key == id) ? o : findById(o.children, id);
}
}
const res = findById(treeData, 14);
console.log(res);
Output:
{
"title": "leaf111",
"key": 14
}
You can use a tree walker, which traverses the tree and calls a provided function upon visiting each node. The provided function could check to see if the node matches the provided ID.
An example:
function getNodeById(id) {
let matchingNode;
walk(tree, node => {
if(node.key === 14) {
matchingNode = node;
}
});
return matchingNode;
}
A tree walker can be implemented using recursion, as you mention. In a preorder operation, which starts at the topmost node, the walker takes the tree (the root node) and on each invocation:
calls the callback function with the current node
for each child node, calls itself with the child node and callback
function walker(node, cb) {
cb(node);
if (Array.isArray(node.children)) {
node.children.forEach(child => walker(child, cb));
}
}
For use with React, you can implement your own walking using React.Children.forEach, or you may prefer try a library like https://github.com/FormidableLabs/react-ssr-prepass.
I have a recipes.js document that has a tag field:
{
name: 'tags',
title: 'Tags',
type: 'array',
of: [{ type: 'reference', to: { type: 'tags' } }],
options: {
layout: 'tags',
},
},
it references another document called tags.js:
export default {
name: 'tags',
type: 'document',
title: 'Tags',
fields: [
{
name: 'title',
title: 'Title',
type: 'string',
},
],
};
I am trying to add the tags to each recipe as an array of strings in graphql. such as:
"tags": ['dinner', 'lunch', 'ribs']
but instead, I get an array of objects:
"tags": [
{
"title": "breakfast"
},
{
"title": "pancakes"
},
{
"title": "food"
}
]
How can I tell sanity all I want is each one to be added in as a string so it is an array of strings and not objects.
Sanity's GraphQL API does not support transforming the data structure into something else. If you want to do that, you will have to use GROQ.
i have to provide type for array of objects using react and typescript?
below is the code,
const SomeComponent = (item: string, children: any) => {
//some logic
}
here as you see for children i have use any type instead i want to use type of its own. when i log children in console its like below an array of objects
[
{
id: '1',
children: [],
},
{
id: '2',
children: [
{
id: '21',
name: 'children1',
},
],
},
]
What should be the type of children instead of any. i am new to using typescript. could someone help me with this. thanks.
If you have defined class or interface Child, you can use
children: Child[]
In general, array of object is noted as object[]
Assuming that children and top level array is not recursive data structure you can use this type:
type Item = {
id: `${number}`;
children: Child[]
}
type Child = {
id: `${number}`;
name: `children${number}`;
}
const arr: Item[] = [
{
id: '1',
children: [],
},
{
id: '2',
children: [
{
id: '21',
name: 'children1',
},
],
},
]
This syntax/type - `${number}` means that it is a string but contains only numbers
I have a huge json file with following structure:
name: 'xxx',
worth: [123, 456, 789]
children: [
{name: 'xxx',
worth: [987, 654, 321],
children: [
{name: 'xxx',
worth: [213, 546, 879],
children: []}
},
{name: 'xxx',
worth: [987, 654, 321],
children: [
name: 'xxx',
worth: [213, 546, 879],
children: []
}],
]
The number of children can get up to 10 layer deep.
I created an angular component that displays name and worth and takes children as an Input to call itself again with the children's name and worth but I get maximum stack size errors with this approach.
How to write a function that can loop through this json until children array is empty and display the name and worth of all of them on the way?
This screams recursion but I cant manage...
Presuming your root object represents a single child, your code would look like this:
const child = {
name: "xxx1",
worth: [123, 456, 789],
children: [
{
name: "xxx2",
worth: [987, 654, 321],
children: [
{
name: "xxx3",
worth: [213, 546, 879],
children: []
}
]
},
{
name: "xxx4",
worth: [987, 654, 321],
children: [
{
name: "xxx5",
worth: [213, 546, 879],
children: []
}
]
}
]
};
const sum = (arr) => arr.reduce((a, b) => a + b, 0);
function process_child(child, result) {
const { name, worth, children } = child;
result.push({ name, worth: sum(worth) });
for (const c of children) {
process_child(c, result);
}
return result;
}
const children = process_child(child, []);
console.table(children);
Here, process_child is a function that takes in a single child and a list of results (initially empty). It populates the list of results while going through all the nested children. The end result is an array of objects with the structure {name, worth}, which you can then consume in whatever way you wish.
This is not an Angular-specific problem, and in fact you will just want your Angular component to be a passive consumer of the data returned by this function.
Here's a working execution on CodeSandbox where the result is simply displayed on the page in JSON form.
i did a request to the API, then the response is as the following:
data1 = [{id: 1, code:1, title:title1}, {id:2, code:3, title:title2}, ...]
Now i would like to extract an array of the titles of the above response as below:
titles = [title1, title2, ....]
how can i do it by map?
And the second question:
Consider if the response would be as follow:
data2 = [{id: 1, code:1, title:title1, chapters:[{id:1, chapter: chapter1},{id:2, chapter: chapter2}, ...]}, {id:4, code:5, title:title3, chapters:[{id:4, chapter: chapter3}, ...]}, ...]
In this case how can i extract an array of the chapters as following:
chapters = [chapter1, chapter2, chapter3]
I tried to do them as below:
for the first question:
title = data1.map((item) => {item.title})
for the second one i did:
chapters = data2.chapters.map((item) => {item.chapter})
But it doesn't work. I think some where there are error in syntaxes.
Can any one help me how to manage these data?
Thank you.
Yep, you are wrong with syntax.
Firs case - title = data1.map((item) => {item.title})
You've wrapped item.title with {}, so you should add return. Or omit {}.
For example: title = data1.map(item => item.title)
Second case - same issue with {}, but you should also use flatMap because you need flat list in result. If you write with regular map - you won't get desired ["chapter1", "chapter2"].
See also detailed example below.
const data1 = [
{ id: 1, code: 1, title: "title1" },
{ id: 2, code: 3, title: "title2" }
];
const data1_mapped = data1.map(d => d.title);
console.log(data1_mapped);
const data2 = [
{
id: 1,
code: 1,
title: "title1",
chapters: [{ id: 1, chapter: "chapter1" }, { id: 2, chapter: "chapter2" }]
},
{
id: 2,
code: 2,
title: "title2",
chapters: [{ id: 1, chapter: "chapter22" }, { id: 2, chapter: "chapter32" }]
}
];
const data2_mapped = data2.flatMap(d => d.chapters.map(c => c.chapter));
console.log(data2_mapped);
You are not returning a value. Try removing braces like so...
title = data1.map((item) => item.title)
chapters = data2.chapters.map((item) => item.chapter)
See this for more info on the issue:
Meaning of curly braces in array.map()