javascript - Javascript: map an array of items and call function for data
问题描述
I am new to javascript. I have an id, name and time that I am trying to get from my data
and for each name I am trying to loop through the data
and call a function from each name. Any help would be much appreciated. Thank you so much!
This is what I have done
const data = [
[
{
"id": "14hyzdrdsquo",
"name": "Ronald",
"time": '12pm',
},
],
[
{
"id": "1f496w43b8yi",
"name": "Jack",
"time": '1am',
},
],
]
const getData = (id, name, time) => {
const ids = [] // desired ['14hyzdrdsquo','1f496w43b8yi']
const names = []// desired ['Ronald','Jack']
const times = []// desired ['12pm','1am']
ids.push(id) // should have each id in this array
names.push(name) // should have each name in this array
times.push(time) // should have each time in this array
}
var id = Math.random().toString(16).slice(2)
data.map(j => j.map(i => getData(id, i.name, i.time)))
解决方案
问题是你提出的
const ids = [] // desired ['14hyzdrdsquo','1f496w43b8yi']
const names = []// desired ['Ronald','Jack']
const times = []// desired ['12pm','1am']
内部getData
函数。这意味着您在调用时创建了新的数组,getData
并且您的解决方案更好地使用 .forEach 而不是 .map。
const data = [
[
{
"id": "14hyzdrdsquo",
"name": "Ronald",
"time": '12pm',
},
],
[
{
"id": "1f496w43b8yi",
"name": "Jack",
"time": '1am',
},
],
]
const ids = [] // desired ['14hyzdrdsquo','1f496w43b8yi']
const names = []// desired ['Ronald','Jack']
const times = []// desired ['12pm','1am']
const getData = (id, name, time) => {
ids.push(id) // should have each id in this array
names.push(name) // should have each name in this array
times.push(time) // should have each time in this array
}
var id = Math.random().toString(16).slice(2)
data.forEach(j => j.forEach(i => getData(id, i.name, i.time)))
console.log(ids)
console.log(names)
console.log(times)
推荐阅读
- dns - 使用 GCE 托管实例组托管 Web 应用程序
- javascript - 重置表单未单击任何按钮 - Angular
- python - SyntaxError:ipython 中的 executable_path 语法无效
- java - 自动按字母顺序对成员变量进行排序
- batch-file - 使用参数延迟shutdown.exe
- bash - Bash 扩展之谜
- kubernetes - 使用 Prometheus 监控自定义 kubernetes pod 指标
- hyperledger-composer - 导入 bna 文件:无法获取链码的包
- java - 返回布尔值的嵌套 for 循环上的死代码
- r - 用不同的 y 标签长度对齐两个图的 x 轴