KAMLESH KUMAR
KAMLESH KUMAR

Reputation: 130

How to make the value of an object of an array as the key of an object of another array

Suppose I have an array like this:

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

Now I want to convert this array to something like following array

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'.

How can I do this?

Upvotes: 1

Views: 53

Answers (4)

Dharmaraj
Dharmaraj

Reputation: 50850

A simple one-liner would be:

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)

Upvotes: 0

adiga
adiga

Reputation: 35222

You could use a mapper object which maps text value to the number. Then use map on the array:

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)

Upvotes: 0

ahsan
ahsan

Reputation: 1504

Just iterate through Array1, check if the text is 'a', then store 1 else store 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)

Upvotes: 2

SaloniMishra
SaloniMishra

Reputation: 194

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;
});

You can use this code for the output you are trying to achieve.

Upvotes: 1

Related Questions