wh gaming
wh gaming

Reputation: 37

Loop through object and push it into new array JavaScript

I want to ask about the JavaScript code of this algorithm, let's say I have an object of cars:

var cars = {
  'civic' : {
    'color' : 'blue',
    'year' : '2020'
  },
  'supra' : {
    'color' : 'red',
    'year' : '2019'
  },
  'impala' : {
    'color' : 'black',
    'year' : '1967'
  },
  'fake_civic' : {
    'color' : 'blue',
    'year' : '2020'
  },
  'fake_supra' : {
    'color' : 'red',
    'year' : '2019'
  },
  'fake_impala' : {
    'color' : 'black',
    'year' : '1967'
  },
}

and i want to extract the fake ones into an array of objects so it would look like this

fakeCars = [
  {'fake_civic' : {
    'color' : 'blue',
    'year' : '2020'
    }
  },
  {'fake_supra' : {
    'color' : 'red',
    'year' : '2019'
    }
  },
  {'fake_impala' : {
    'color' : 'black',
    'year' : '1967'
    }
  },
];

i've tried this

fakeCars = Object.entries(cars).map((e) => ( { [e[0]]: e[1] } ));

but it returns an array for the whole cars object, i don't know how to search for the fake ones, how i can i solve this? thank you.

Upvotes: 0

Views: 61

Answers (2)

AlexAV-dev
AlexAV-dev

Reputation: 1175

const cars = {
  'civic' : {
    'color' : 'blue',
    'year' : '2020'
  },
  'supra' : {
    'color' : 'red',
    'year' : '2019'
  },
  'impala' : {
    'color' : 'black',
    'year' : '1967'
  },
  'fake_civic' : {
    'color' : 'blue',
    'year' : '2020'
  },
  'fake_supra' : {
    'color' : 'red',
    'year' : '2019'
  },
  'fake_impala' : {
    'color' : 'black',
    'year' : '1967'
  },
}

const fakeCars = Object.keys(cars).reduce((acc, rec) => {
  return (rec.indexOf('fake') > -1) ? [...acc, { [rec]: cars[rec] }] : acc
}, [])

console.log(fakeCars)

Upvotes: 0

norbitrial
norbitrial

Reputation: 15166

I would use .filter() for this purpose as:

var cars = { 'civic' : { 'color' : 'blue', 'year' : '2020' }, 'supra' : { 'color' : 'red',  'year' : '2019'  }, 'impala' : {   'color' : 'black',        'year' : '1967'  },  'fake_civic' : {  'color' : 'blue',  'year' : '2020'      },      'fake_supra' : { 'color' : 'red',    'year' : '2019'  }, 'fake_impala' : { 'color' : 'black',  'year' : '1967' },  }

const result = Object.entries(cars)
                     .filter(e => e[0].includes('fake'));

console.log(result);

Upvotes: 5

Related Questions