我的json如下:
[{"id":19,"text":"A-Z CLI 19/03/2015"},{"id":36,"text":"Wavetel Retail1"},{"id":37,"text":"Wavetel A2Z Platinum"},{"id":38,"text":"Wavetel A2Z Gold"},{"id":40,"text":"mysql test2"},{"id":63,"text":"inbound test"},{"id":137,"text":"testpbxretail"},{"id":144,"text":"INBOUND CLI"},{"id":145,"text":"0800142324"},{"id":164,"text":"Rategenerator-Otto-Test"},{"id":165,"text":"Rategenerator-Otto-Test 2 "},{"id":166,"text":"Rategenerator-Otto-Test 3 "},{"id":171,"text":"VasimRateGenerator"}]

我想要使用第一个元素值(19)作为第二个元素的键的最短路径(而不是' text')有多个元素,因此可以通过循环完成。然后删除第一个元素。
所以我想要输出如下(例如第一个元素[{" id":19," text":" AZ CLI 19/03/2015" }]):
[{"19":"A-Z CLI 19/03/2015"}]

答案 0 :(得分:3)
您可以通过传递map
函数作为参数来使用callback
方法。
let arr = [{"id":19,"text":"A-Z CLI 19/03/2015"},{"id":36,"text":"Wavetel Retail1"},{"id":37,"text":"Wavetel A2Z Platinum"},{"id":38,"text":"Wavetel A2Z Gold"},{"id":40,"text":"mysql test2"},{"id":63,"text":"inbound test"},{"id":137,"text":"testpbxretail"},{"id":144,"text":"INBOUND CLI"},{"id":145,"text":"0800142324"},{"id":164,"text":"Rategenerator-Otto-Test"},{"id":165,"text":"Rategenerator-Otto-Test 2 "},{"id":166,"text":"Rategenerator-Otto-Test 3 "},{"id":171,"text":"VasimRateGenerator"}]
arr = arr.map(function({id, text}){
return { [id]: text };
});
console.log(arr);

或只使用一个arrow
功能。
let arr = [{"id":19,"text":"A-Z CLI 19/03/2015"},{"id":36,"text":"Wavetel Retail1"},{"id":37,"text":"Wavetel A2Z Platinum"},{"id":38,"text":"Wavetel A2Z Gold"},{"id":40,"text":"mysql test2"},{"id":63,"text":"inbound test"},{"id":137,"text":"testpbxretail"},{"id":144,"text":"INBOUND CLI"},{"id":145,"text":"0800142324"},{"id":164,"text":"Rategenerator-Otto-Test"},{"id":165,"text":"Rategenerator-Otto-Test 2 "},{"id":166,"text":"Rategenerator-Otto-Test 3 "},{"id":171,"text":"VasimRateGenerator"}]
arr = arr.map(({id, text}) => ({[id]: text}));
console.log(arr);