Как сделать значение объекта массива ключом объекта другого массива

#javascript

Вопрос:

Предположим, у меня есть массив, подобный этому:

 array1 = [
{date: '1', text: 'a'},
{date: '2', text: 'b'},
{date: '3', text: 'a'},
{date: '4', text: 'b'}
];
// text will be either 'a' or 'b'
// basically, here date denotes the dates of a month, so it could be up to 28 or 29 or 30 or 31
 

Теперь я хочу преобразовать этот массив во что-то вроде следующего массива

 array2 = [
{1: '1'},
{2: '0'},
{3: '1'},
{4: '0'}
];
// For each value of array1, value of date (1,2,3,4) becomes keys here. If text was 'a', it should convert to '1' and if it was 'b', it should convert to '0'.
 

Как я могу это сделать?

Ответ №1:

Просто выполните итерацию по массиву 1, проверьте, является ли текст «a», затем сохраните 1, а затем сохраните 0.

 const array1 = [
{date: '1', text: 'a'},
{date: '2', text: 'b'},
{date: '3', text: 'a'},
{date: '4', text: 'b'}
];

let newArray = {};

for(let i=0; i<array1.length; i  ){
    if(array1[i]["text"] === 'a'){
    newArray[array1[i]["date"]] = 1;
  } else {
    newArray[array1[i]["date"]] = 0;
  }
}

console.log(newArray) 

Ответ №2:

 const array2 = array1.map(value => {
   let newValue;
   if(value.text === 'a') {
      newValue = 1;
   } else if(value.text === 'b') {
      newValue = 0;
   }
   let newObj = {};
   newObj[value.date] = newValue;
   return newObj;
});
 

Вы можете использовать этот код для вывода, которого вы пытаетесь достичь.

Ответ №3:

Вы можете использовать mapper объект, который сопоставляет text значение с числом. Затем используйте map в массиве:

 const array = [{date:"1",text:"a"},{date:"2",text:"b"},{date:"3",text:"a"},{date:"4",text:"b"}],
      mapper = { a: '1', b: '0' },
      output = array.map(o => ({ [o.date]: mapper[o.text] }))

console.log(output) 

Ответ №4:

Простой однострочный был бы:

 const array1 = [
  {date: '1', text: 'a'},
  {date: '2', text: 'b'},
  {date: '3', text: 'a'},
  {date: '4', text: 'b'}
];

const array2 = array1.map(({date, text}) => ({[date]: text === "a" ? "1" : "0"}))

console.log(array2)