Home > Back-end >  Within an array of objects modify all previous objects to an object with a specific property
Within an array of objects modify all previous objects to an object with a specific property

Time:02-24

I have an array of objects, and according to a property inserted in one of them i would like to mark or select all the objects previous to that object container of the specific property

My array is in this way:

const arrX= [
      { status: '1' },
      { status: '2'},
      { status: '3', imHere: true },
      { status: '4' },
    ];

Then due to the property imHere on arrX[2], the positions arrX[0] and arrX[1] should be modified.

My expected result would be :

const arrX= [
      { status: '1',wasHere:true },
      { status: '2',wasHere:true},
      { status: '3', imHere: true },
      { status: '4' },
    ];

I know that the map method would be quite useful in this case, but can´t find the way to check from index of object containing imHere backwards the former positions

CodePudding user response:

Here's one method for it using Array#reduce and a boolean to track whether we've encountered inHere

const arrX = [
  {status: '1'},
  {status: '2'},
  {status: '3',imHere: true},
  {status: '4'},
];

let found = false,
  updated = arrX.reduce((b, a) => {
    found = found || (a.hasOwnProperty('imHere') && a.imHere === true)
    if (!found) a.wasHere = true;
    return b.concat(a);
  }, [])

console.log(updated)

CodePudding user response:

A simple loop - breaking out of it when one of the objects contains imHere, otherwise adding in a wasHere property.

function update(arr) {
  for (let i = 0; i < arr.length; i  ) {
    if (!arr[i].imHere) {
      arr[i].wasHere = true;
    } else {
      break;
    }
  }
  return arr;
}

const arr = [
  { status: '1' },
  { status: '2' },
  { status: '3', imHere: true },
  { status: '4' },
];

console.log(update(arr));

CodePudding user response:

One approach is to use .findIndex() and .map():

const arrX= [{ status: '1' }, { status: '2'}, { status: '3', imHere: true }, { status: '4'}];

const imHereIndex = arrX.findIndex(({imHere}) => imHere === true);
const result = arrX.map((val, index) => index < imHereIndex
     ? { ...val, wasHere: true }
     : val
);

console.log(result);

CodePudding user response:

Even if @Kinglish answer works like a charm I want to share another way to achieve your goal. This road is surely longer than Kinglish ones, never then less is a good alternative.

      { status: '4' },
    ];
    
function findProperty(arr) {
  const hasProperty = arr.findIndex(el => Object.keys(el).includes('imHere'))
  const addNewProperty = arr.map((el,i) => (i < hasProperty) ? {...el, wasHere: true} : el)
  
  return addNewProperty
}

const updatedArray = findProperty(arrX)
console.log(updatedArray)
  • Related