简体   繁体   中英

trying to create an array of objects given 2 arrays + map

I have the following 2 arrays here:

  > chNameArr
[ 'chanel1',
  'chanel2',
  'chanel3',
  'chanel4',
  'chanel5',
  'chanel6',
  'chanel7' ]

and here:

   > a
[ 'channelName'
  'status',
  'connections',
  'socketIds',
  'lastRun',
  'numberOfRuns',
  'timeout' ]

what I am trying to achieve is the following objects per channel in an array where channelName from a get the value from chNameArr but the rest of 'a' gets an empty string

 file=[{"channelName":"chanel1","status":"", "connections":"", "socketIds":"", "lastRun":"", "numberOfRuns":"", "timeout":""},
 .
 .
 .
        {"channelName":"chanel7","status":"", "connections":"", "socketIds":"", "lastRun":"", "numberOfRuns":"", "timeout":""}]

this is my attempt

   > chNameArr.map(function(d){return {channelName:d}})
[ { channelName: 'chanel1' },
  { channelName: 'chanel2' },
  { channelName: 'chanel3' },
  { channelName: 'chanel4' },
  { channelName: 'chanel5' },
  { channelName: 'chanel6' },
  { channelName: 'chanel7' } ]
chNameArr.map(function(d) {
  result = {};
  result[a[0]] = d;
  for (var i=1; i<a.length; i++) {
    result[a[i]] = "";
  }
  return result;
})

There is no one-liner to solve this problem in general, although if you don't actually need to use the array a you could manually construct {channelName:d, status: "", ...} in your original map.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM