0

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.

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

it works just fine, looking deeper into array.filter and string.includes method, thank you.
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.