#javascript #arrays #json #object
#javascript #массивы #json #объект
Вопрос:
У меня следующая проблема, мне нужно добавить новую пару ключей и значений к каждому объекту в этом списке,
module.exports = [
{"A": "P17060024503", "B": "6/14/2017 21:54", "C": "4", "D": "10", "E": "", "F": "14TH", "G": "ST", "H": "10 14TH ST, San Diego, CA", "I": "1151", "J": "O", "K": "521", "L": "2", "M": "32.7054489", "N": "-117.1518696"},
{ "A": "P17030051227", "B": "3/29/2017 22:24", "C": "4", "D": "10", "E": "", "F": "14TH", "G": "ST", "H": "10 14TH ST, San Diego, CA", "I": "1016", "J": "A", "K": "521", "L": "2", "M": "32.7054544", "N": "-117.1467137"},
{ "A": "P17060004814", "B": "6/3/2017 18:04", "C": "7", "D": "10", "E": "", "F": "14TH", "G": "ST", "H": "10 14TH ST, San Diego, CA", "I": "1016", "J": "A", "K": "521", "L": "2", "M": "32.7053961", "N": "-117.1444185"},
{ "A": "P17030029336", "B": "3/17/2017 10:57", "C": "6", "D": "10", "E": "", "F": "14TH", "G": "ST", "H": "10 14TH ST, San Diego, CA", "I": "1151", "J": "OT", "K": "521", "L": "2", "M": "32.7054244", "N": "-117.1425917"},
{ "A": "P17030005412", "B": "3/3/2017 23:45", "C": "6", "D": "10", "E": "", "F": "15TH", "G": "ST", "H": "10 15TH ST, San Diego, CA", "I": "911P", "J": "CAN", "K": "521", "L": "2", "M": "32.7055067", "N": "-117.1405936"},
{ "A": "P17020016091", "B": "2/10/2017 8:23", "C": "6", "D": "10", "E": "", "F": "15TH", "G": "ST", "H": "10 15TH ST, San Diego, CA", "I": "AU2", "J": "W", "K": "521", "L": "2", "M": "32.7055067", "N": "-117.1405936"},
{ "A": "P17040017368", "B": "4/11/2017 4:57", "C": "3", "D": "10", "E": "", "F": "15TH", "G": "ST", "H": "10 15TH ST, San Diego, CA", "I": "5150", "J": "CAN", "K": "521", "L": "2", "M": "32.7055067", "N": "-117.1405936"},
{ "A": "P17030048050", "B": "3/28/2017 6:30", "C": "3", "D": "10", "E": "", "F": "15TH", "G": "ST", "H": "10 15TH ST, San Diego, CA", "I": "1146", "J": "K", "K": "521", "L": "", "M": "32.711212", "N": "-117.1336713"},
{ "A": "P17060037341", "B": "6/22/2017 10:19", "C": "5", "D": "10", "E": "", "F": "15TH", "G": "ST", "H": "10 15TH ST, San Diego, CA", "I": "242", "J": "K", "K": "521", "L": "1", "M": "32.7058661", "N": "-117.132085"},
{ "A": "P17060008467", "B": "6/5/2017 19:27", "C": "2", "D": "10", "E": "", "F": "15TH", "G": "ST", "H": "10 15TH ST, San Diego, CA", "I": "5150", "J": "K", "K": "521", "L": "2", "M": "32.7093133", "N": "-117.12756"},
Я хочу добавить «O» :
O — это мой ключ к каждому объекту сверху, а мое значение — любое из этого списка ARRIVE ON SCENE
PRISONER IN CUSTODY
PTU (PRISONER TRANSPORT)
SHOPLIFTER/QUICK CITE
BORDERPRISONERTRANSPORT
RETURN TO STATION
PHONE YOUR STATION
PHONE YOUR HOME
SECURE, END OF SHIFT
AUTO THEFT
EVAL-POSS UNREPORTED CAR THEFT
CAR THEFT REPORT
CAR THEFT RECOVERY REPORT
TAMPERING W/VEH IN PROGRESS
VEHICLE ALARM/AUDIBLE
VEHICLE CASER
TAMPERING W/VEH REPORT
MEET OFFICER 10-10
DISCHARGING FIREARMS
PROWLER
PERSON DOWN
REPORT OF CRIME OCCD MEXICO
CHECK THE AREA
BALL GAME IN STREET(83 03MC)
INCOMPLETE PHONE CALL
CALLING FOR HELP
CALLING FOR HELP-PANIC ALARM
AMBULANCE CALL, OVERDOSE
в идеале это выглядит так
"O" : "PRISONER IN CUSTODY"},
... "O": "Shoplifter/Quick Cite"},
.... "O": "Return TO Station"}, etc
Комментарии:
1. является ли значение
O
случайным элементом из вашего списка или оно основано на индексе объекта?2. Извините, но
BALL GAME IN STREET(83 03MC)
это довольно забавно в контексте этого списка.3. @NickParsons на данный момент это может быть случайный элемент, на самом деле, если вы посмотрите на мой «I»: «1151» в моем объекте , который должен соответствовать моему определенному коду преступления, но пока это может быть случайный элемент из списка, есть идеи, как на самом деле сопоставить каждое преступление с соответствующим кодом, не используя так много if elses .
4. @DavidArriaga вы могли бы использовать другой объект. Но каковы коды преступлений для каждого из перечисленных вами преступлений?
5. @ggorlen хаха, его данные о преступлениях, это могут быть буквально люди, играющие в баскетбол на улице с пробками
Ответ №1:
Вы можете сохранить свой новый список в array
oValues=[
'ARRIVE ON SCENE',
'PRISONER IN CUSTODY',
'PTU (PRISONER TRANSPORT)'
.
.
.]
А затем присвоить значения oValues основному списку, как показано ниже
module.exports.forEach((item,index)=>{item['O']=oValues[index]})
Предполагая, что вам нужно последовательно присвоить значение ‘O’
Ответ №2:
Поскольку вы хотите добавить любой элемент из списка, просто map
сделайте это вот так:
const data = [{
"A": "P17060024503",
"B": "6/14/2017 21:54",
"C": "4",
"D": "10",
"E": "",
"F": "14TH",
"G": "ST",
"H": "10 14TH ST, San Diego, CA",
"I": "1151",
"J": "O",
"K": "521",
"L": "2",
"M": "32.7054489",
"N": "-117.1518696"
}, {
"A": "P17030051227",
"B": "3/29/2017 22:24",
"C": "4",
"D": "10",
"E": "",
"F": "14TH",
"G": "ST",
"H": "10 14TH ST, San Diego, CA",
"I": "1016",
"J": "A",
"K": "521",
"L": "2",
"M": "32.7054544",
"N": "-117.1467137"
}, {
"A": "P17060004814",
"B": "6/3/2017 18:04",
"C": "7",
"D": "10",
"E": "",
"F": "14TH",
"G": "ST",
"H": "10 14TH ST, San Diego, CA",
"I": "1016",
"J": "A",
"K": "521",
"L": "2",
"M": "32.7053961",
"N": "-117.1444185"
}, {
"A": "P17030029336",
"B": "3/17/2017 10:57",
"C": "6",
"D": "10",
"E": "",
"F": "14TH",
"G": "ST",
"H": "10 14TH ST, San Diego, CA",
"I": "1151",
"J": "OT",
"K": "521",
"L": "2",
"M": "32.7054244",
"N": "-117.1425917"
}, {
"A": "P17030005412",
"B": "3/3/2017 23:45",
"C": "6",
"D": "10",
"E": "",
"F": "15TH",
"G": "ST",
"H": "10 15TH ST, San Diego, CA",
"I": "911P",
"J": "CAN",
"K": "521",
"L": "2",
"M": "32.7055067",
"N": "-117.1405936"
}, {
"A": "P17020016091",
"B": "2/10/2017 8:23",
"C": "6",
"D": "10",
"E": "",
"F": "15TH",
"G": "ST",
"H": "10 15TH ST, San Diego, CA",
"I": "AU2",
"J": "W",
"K": "521",
"L": "2",
"M": "32.7055067",
"N": "-117.1405936"
}, {
"A": "P17040017368",
"B": "4/11/2017 4:57",
"C": "3",
"D": "10",
"E": "",
"F": "15TH",
"G": "ST",
"H": "10 15TH ST, San Diego, CA",
"I": "5150",
"J": "CAN",
"K": "521",
"L": "2",
"M": "32.7055067",
"N": "-117.1405936"
}, {
"A": "P17030048050",
"B": "3/28/2017 6:30",
"C": "3",
"D": "10",
"E": "",
"F": "15TH",
"G": "ST",
"H": "10 15TH ST, San Diego, CA",
"I": "1146",
"J": "K",
"K": "521",
"L": "",
"M": "32.711212",
"N": "-117.1336713"
}, {
"A": "P17060037341",
"B": "6/22/2017 10:19",
"C": "5",
"D": "10",
"E": "",
"F": "15TH",
"G": "ST",
"H": "10 15TH ST, San Diego, CA",
"I": "242",
"J": "K",
"K": "521",
"L": "1",
"M": "32.7058661",
"N": "-117.132085"
}, {
"A": "P17060008467",
"B": "6/5/2017 19:27",
"C": "2",
"D": "10",
"E": "",
"F": "15TH",
"G": "ST",
"H": "10 15TH ST, San Diego, CA",
"I": "5150",
"J": "K",
"K": "521",
"L": "2",
"M": "32.7093133",
"N": "-117.12756"
}];
const newItems = [
"ARRIVE ON SCENE",
"PRISONER IN CUSTODY",
"PTU (PRISONER TRANSPORT)",
"SHOPLIFTER/QUICK CITE",
"BORDERPRISONERTRANSPORT",
"RETURN TO STATION",
"PHONE YOUR STATION",
"PHONE YOUR HOME",
"SECURE, END OF SHIFT",
"AUTO THEFT",
"EVAL-POSS UNREPORTED CAR THEFT",
"CAR THEFT REPORT",
"CAR THEFT RECOVERY REPORT",
"TAMPERING W/VEH IN PROGRESS",
"VEHICLE ALARM/AUDIBLE",
"VEHICLE CASER",
"TAMPERING W/VEH REPORT",
"MEET OFFICER 10-10",
"DISCHARGING FIREARMS",
"PROWLER",
"PERSON DOWN",
"REPORT OF CRIME OCCD MEXICO",
"CHECK THE AREA",
"BALL GAME IN STREET(83 03MC)",
"INCOMPLETE PHONE CALL",
"CALLING FOR HELP",
"CALLING FOR HELP-PANIC ALARM",
"AMBULANCE CALL, OVERDOSE"
];
const output = data.map(o => ({ ...o,
O: newItems[Math.floor(Math.random() * newItems.length)]
}));
console.log(output);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Синтаксис ES5:
var data = [{
"A": "P17060024503",
"B": "6/14/2017 21:54",
"C": "4",
"D": "10",
"E": "",
"F": "14TH",
"G": "ST",
"H": "10 14TH ST, San Diego, CA",
"I": "1151",
"J": "O",
"K": "521",
"L": "2",
"M": "32.7054489",
"N": "-117.1518696"
}, {
"A": "P17030051227",
"B": "3/29/2017 22:24",
"C": "4",
"D": "10",
"E": "",
"F": "14TH",
"G": "ST",
"H": "10 14TH ST, San Diego, CA",
"I": "1016",
"J": "A",
"K": "521",
"L": "2",
"M": "32.7054544",
"N": "-117.1467137"
}, {
"A": "P17060004814",
"B": "6/3/2017 18:04",
"C": "7",
"D": "10",
"E": "",
"F": "14TH",
"G": "ST",
"H": "10 14TH ST, San Diego, CA",
"I": "1016",
"J": "A",
"K": "521",
"L": "2",
"M": "32.7053961",
"N": "-117.1444185"
}, {
"A": "P17030029336",
"B": "3/17/2017 10:57",
"C": "6",
"D": "10",
"E": "",
"F": "14TH",
"G": "ST",
"H": "10 14TH ST, San Diego, CA",
"I": "1151",
"J": "OT",
"K": "521",
"L": "2",
"M": "32.7054244",
"N": "-117.1425917"
}, {
"A": "P17030005412",
"B": "3/3/2017 23:45",
"C": "6",
"D": "10",
"E": "",
"F": "15TH",
"G": "ST",
"H": "10 15TH ST, San Diego, CA",
"I": "911P",
"J": "CAN",
"K": "521",
"L": "2",
"M": "32.7055067",
"N": "-117.1405936"
}, {
"A": "P17020016091",
"B": "2/10/2017 8:23",
"C": "6",
"D": "10",
"E": "",
"F": "15TH",
"G": "ST",
"H": "10 15TH ST, San Diego, CA",
"I": "AU2",
"J": "W",
"K": "521",
"L": "2",
"M": "32.7055067",
"N": "-117.1405936"
}, {
"A": "P17040017368",
"B": "4/11/2017 4:57",
"C": "3",
"D": "10",
"E": "",
"F": "15TH",
"G": "ST",
"H": "10 15TH ST, San Diego, CA",
"I": "5150",
"J": "CAN",
"K": "521",
"L": "2",
"M": "32.7055067",
"N": "-117.1405936"
}, {
"A": "P17030048050",
"B": "3/28/2017 6:30",
"C": "3",
"D": "10",
"E": "",
"F": "15TH",
"G": "ST",
"H": "10 15TH ST, San Diego, CA",
"I": "1146",
"J": "K",
"K": "521",
"L": "",
"M": "32.711212",
"N": "-117.1336713"
}, {
"A": "P17060037341",
"B": "6/22/2017 10:19",
"C": "5",
"D": "10",
"E": "",
"F": "15TH",
"G": "ST",
"H": "10 15TH ST, San Diego, CA",
"I": "242",
"J": "K",
"K": "521",
"L": "1",
"M": "32.7058661",
"N": "-117.132085"
}, {
"A": "P17060008467",
"B": "6/5/2017 19:27",
"C": "2",
"D": "10",
"E": "",
"F": "15TH",
"G": "ST",
"H": "10 15TH ST, San Diego, CA",
"I": "5150",
"J": "K",
"K": "521",
"L": "2",
"M": "32.7093133",
"N": "-117.12756"
}];
var newItems = [
"ARRIVE ON SCENE",
"PRISONER IN CUSTODY",
"PTU (PRISONER TRANSPORT)",
"SHOPLIFTER/QUICK CITE",
"BORDERPRISONERTRANSPORT",
"RETURN TO STATION",
"PHONE YOUR STATION",
"PHONE YOUR HOME",
"SECURE, END OF SHIFT",
"AUTO THEFT",
"EVAL-POSS UNREPORTED CAR THEFT",
"CAR THEFT REPORT",
"CAR THEFT RECOVERY REPORT",
"TAMPERING W/VEH IN PROGRESS",
"VEHICLE ALARM/AUDIBLE",
"VEHICLE CASER",
"TAMPERING W/VEH REPORT",
"MEET OFFICER 10-10",
"DISCHARGING FIREARMS",
"PROWLER",
"PERSON DOWN",
"REPORT OF CRIME OCCD MEXICO",
"CHECK THE AREA",
"BALL GAME IN STREET(83 03MC)",
"INCOMPLETE PHONE CALL",
"CALLING FOR HELP",
"CALLING FOR HELP-PANIC ALARM",
"AMBULANCE CALL, OVERDOSE"
];
var output = data.map(function(o) {
o.O = newItems[Math.floor(Math.random() * newItems.length)];
return o;
});
console.log(output);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Комментарии:
1. вау! как вы разделили запятую и отформатировали массив NewItems??
2. Я добавил запятые и кавычки — разве это не то, что вы хотели? О — У фрагментов стека есть опция массового редактирования — при щелчке по команде создается новый курсор.
3. хорошо, спасибо, это было здорово, на самом деле у меня есть больший список из 300 элементов, но я хочу преобразовать его в массив, как вы сделали, но не могу найти опцию массового редактирования
4. Вот как вы это делаете — переходите к последнему элементу в массиве, щелкаете по команде в начале строки, щелкаете по команде в начале каждого элемента в массиве, вставляете кавычку, переходите к концу элемента, вставляете другую кавычку, вставляете запятую.
5. Также @DavidArriaga если мой ответ устранил вашу проблему, пожалуйста, отметьте его как принятый, щелкнув серую галочку слева от моего ответа.
Ответ №3:
Сделайте это. В чем ваша проблема, на самом деле?
var arr = [/*your array*/];
function getRandomO() {/*returns your random O*/}
arr.forEach(v=>v.O = getRandomO());
module.exports = arr;
Если вы хотите, чтобы JSON делал JSON.stringify(arr)
в консоли и копировал результат.
Ответ №4:
Попробуйте с помощью Array#map
и Array#forEach
.
- Я не
t know the structure of your second array.So created with array object.Then map the
присваиваю значение array. - Затем примените forEach к массиву one. Наконец, добавьте значение на основе индекса
var arr =[
{"A": "P17060024503", "B": "6/14/2017 21:54", "C": "4", "D": "10", "E": "", "F": "14TH", "G": "ST", "H": "10 14TH ST, San Diego, CA", "I": "1151", "J": "O", "K": "521", "L": "2", "M": "32.7054489", "N": "-117.1518696"},
{ "A": "P17030051227", "B": "3/29/2017 22:24", "C": "4", "D": "10", "E": "", "F": "14TH", "G": "ST", "H": "10 14TH ST, San Diego, CA", "I": "1016", "J": "A", "K": "521", "L": "2", "M": "32.7054544", "N": "-117.1467137"}
];
var arr2 = [{'ss':'sss','o':'something1'},{'hh':'dd','o':'something2'}]
arr2_filter_o = arr2.map(a=> a.o);
//its like ['something1','something2']
arr.forEach((a,b)=> {
a['o']=arr2_filter_o[b];
})
console.log(arr)
Комментарии:
1. есть какой-нибудь способ рандомизировать данные в качестве моего значения из этого списка, который я опубликовал, кодов преступлений? кстати, кто-нибудь знает, где я могу сгенерировать массив, просто вставив crimes
2. какой формат вашего типа данных — массив
[2,3]
или объект[{w},{e}]
. Смотрите мой комментарий во фрагменте
Ответ №5:
Вы можете использовать .forEach
цикл для добавления O
атрибута к каждому из ваших объектов при экспорте. Это будет линейно (O (N)), поскольку вы выполняете итерацию по своим объектам только один раз.
const crimes = ["ARRIVE ON SCENE", "PRISONER IN CUSTODY", "PTU (PRISONER TRANSPORT)", "SHOPLIFTER/QUICK CITE", "BORDERPRISONERTRANSPORT", "RETURN TO STATION", "PHONE YOUR STATION", "PHONE YOUR HOME", "SECURE, END OF SHIFT", "AUTO THEFT", "EVAL-POSS UNREPORTED CAR THEFT", "CAR THEFT REPORT", "CAR THEFT RECOVERY REPORT", "TAMPERING W/VEH IN PROGRESS", "VEHICLE ALARM/AUDIBLE", "VEHICLE CASER", "TAMPERING W/VEH REPORT", "MEET OFFICER 10-10", "DISCHARGING FIREARMS", "PROWLER", "PERSON DOWN", "REPORT OF CRIME OCCD MEXICO", "CHECK THE AREA", "BALL GAME IN STREET(83 03MC)", "INCOMPLETE PHONE CALL", "CALLING FOR HELP", "CALLING FOR HELP-PANIC ALARM", "AMBULANCE CALL, OVERDOSE"];
const exports = [{A:"P17060024503",B:"6/14/2017 21:54",C:"4",D:"10",E:"",F:"14TH",G:"ST",H:"10 14TH ST, San Diego, CA",I:"1151",J:"O",K:"521",L:"2",M:"32.7054489",N:"-117.1518696"},{A:"P17030051227",B:"3/29/2017 22:24",C:"4",D:"10",E:"",F:"14TH",G:"ST",H:"10 14TH ST, San Diego, CA",I:"1016",J:"A",K:"521",L:"2",M:"32.7054544",N:"-117.1467137"},{A:"P17060004814",B:"6/3/2017 18:04",C:"7",D:"10",E:"",F:"14TH",G:"ST",H:"10 14TH ST, San Diego, CA",I:"1016",J:"A",K:"521",L:"2",M:"32.7053961",N:"-117.1444185"},{A:"P17030029336",B:"3/17/2017 10:57",C:"6",D:"10",E:"",F:"14TH",G:"ST",H:"10 14TH ST, San Diego, CA",I:"1151",J:"OT",K:"521",L:"2",M:"32.7054244",N:"-117.1425917"},{A:"P17030005412",B:"3/3/2017 23:45",C:"6",D:"10",E:"",F:"15TH",G:"ST",H:"10 15TH ST, San Diego, CA",I:"911P",J:"CAN",K:"521",L:"2",M:"32.7055067",N:"-117.1405936"},{A:"P17020016091",B:"2/10/2017 8:23",C:"6",D:"10",E:"",F:"15TH",G:"ST",H:"10 15TH ST, San Diego, CA",I:"AU2",J:"W",K:"521",L:"2",M:"32.7055067",N:"-117.1405936"},{A:"P17040017368",B:"4/11/2017 4:57",C:"3",D:"10",E:"",F:"15TH",G:"ST",H:"10 15TH ST, San Diego, CA",I:"5150",J:"CAN",K:"521",L:"2",M:"32.7055067",N:"-117.1405936"},{A:"P17030048050",B:"3/28/2017 6:30",C:"3",D:"10",E:"",F:"15TH",G:"ST",H:"10 15TH ST, San Diego, CA",I:"1146",J:"K",K:"521",L:"",M:"32.711212",N:"-117.1336713"},{A:"P17060037341",B:"6/22/2017 10:19",C:"5",D:"10",E:"",F:"15TH",G:"ST",H:"10 15TH ST, San Diego, CA",I:"242",J:"K",K:"521",L:"1",M:"32.7058661",N:"-117.132085"},{A:"P17060008467",B:"6/5/2017 19:27",C:"2",D:"10",E:"",F:"15TH",G:"ST",H:"10 15TH ST, San Diego, CA",I:"5150",J:"K",K:"521",L:"2",M:"32.7093133",N:"-117.12756"}];
exports.forEach(obj => {
const randomIndex = Math.floor(Math.random() * crimes.length);
obj["O"] = crimes[randomIndex];
});
console.log(exports);
.as-console-wrapper {max-height: 100% !important; top: 0;} /* ignore css */
Ответ №6:
Разбейте решение на список ассоциативных массивов или словарей:
let list = [{},{},{} ... ]
Доступ к n-му элементу этого массива: list[n]
Таким образом, если вы хотите добавить новую пару ключ / значение с индексом n:
list[n]['key'] = value
let text = ['PRISONER IN CUSTODY', 'PTU (PRISONER TRANSPORT)' ... ]
for(t in text) {
let key = 'O'
let value = text[t]
list[t][key] = value
}