-2

Here is my sample object:

name: 'Jango',
age: 23,
sex: 'male',
phone_0: '0000000',
phone_1: '1111111',
phone_2: '2222222'

on the above object, I want to look for is there any field exist with 'phone_', if exist, I want them to be plucked to another array or object.

How to do this in Javascript?

Note: I am inside a react component.

Jithesh Kt
  • 2,023
  • 6
  • 32
  • 48
  • 1
    [Working with objects - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects) – Andreas Jun 22 '18 at 05:56
  • Possible duplicate: https://stackoverflow.com/questions/1098040/checking-if-a-key-exists-in-a-javascript-object – Michael Harley Jun 22 '18 at 05:56

2 Answers2

2

You can convert the object into array using Object.entries. Use reduce to loop thru the array. Use includes to check if the string contains a substring.

let obj = {
  name: 'Jango',
  age: 23,
  sex: 'male',
  phone_0: '0000000',
  phone_1: '1111111',
  phone_2: '2222222'
}

let result = Object.entries(obj).reduce((c, [k, v]) => {
  if (k.includes('phone_')) c[k] = v;
  return c;
}, {});

console.log(result);

You can also use if you want to check if phone_ is in the start of the key.

substr( k, 0, 6 ) === "phone_"
Eddie
  • 26,593
  • 6
  • 36
  • 58
0
const required = _.pick(Object.keys(item).filter(
    key=> key.startsWith(‘phone_’)
    );

_ is lodash library.

yeshashah
  • 1,536
  • 11
  • 19