首页 > 解决方案 > 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)))

标签: javascriptarraysobject

解决方案


问题是你提出的

   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)

推荐阅读