数组对象内部的JavaScript Map数组

时间:2019-03-04 07:43:00

标签: javascript

我有以下JSON数组对象:

const arrayExample = [
            {
                key: 5, 
                children:[
                    {
                        key: 51,
                        title: 'Create User'
                    },
                    {
                        key: 52,
                        title: 'Edit User'

                    }
                ]
            },{
                key: 2, 
                children:[
                    {
                        key: 21,
                        title: 'Create Email'
                    },
                    {
                        key: 22,
                        title: 'Edit Email'

                    }
                ]
            }
        ];

每个数组都包含一个键,

如何在儿童的数组键中使用JavaScript map()函数并获得如下响应?:

const expectedResult = [
            {key:5, children: [51,52]},
            {key:2, children: [21,22]}
        ];

3 个答案:

答案 0 :(得分:-1)

您可以使用嵌套的map()

做些什么

const arr = [
            {
                key: 5, 
                children:[
                    {
                        key: 51,
                        title: 'Create User'
                    },
                    {
                        key: 52,
                        title: 'Edit User'

                    }
                ]
            },{
                key: 2, 
                children:[
                    {
                        key: 21,
                        title: 'Create Email'
                    },
                    {
                        key: 22,
                        title: 'Edit Email'

                    }
                ]
            }
        ];
let result = arr.map(x => (({...x,children:x.children.map(a => a.key)})))
console.log(result);

答案 1 :(得分:-1)

const expectedResult = arrayExample.map((item) => {

   const keyOnlyArray = [];

   item.children.map((children) => {
       keyOnlyArray.push(children.key)    
   })

   return {
      key : item.key,
      children : keyOnlyArray
   }                                                                          
})

答案 2 :(得分:-2)

一种方法是两次使用map,一次是在每个对象内部创建children数组,一次是使用keys键和children < / p>

const arrayExample = [{
  key: 5,
  children: [{
      key: 51,
      title: 'Create User'
    },
    {
      key: 52,
      title: 'Edit User'

    }
  ]
}, {
  key: 2,
  children: [{
      key: 21,
      title: 'Create Email'
    },
    {
      key: 22,
      title: 'Edit Email'

    }
  ]
}];


let expectedResult = arrayExample.map(function(item) {

  return {
    key: item.key,
    // children is an array , so again using map to get an array of key's value
    children: item.children.map(function(childKey) {
      return childKey.key

    })

  }
});

console.log(expectedResult)