Oliver D
Oliver D

Reputation: 2889

How can I push the state to an array with specific items?

I have in the state most of the item I wanted to push it in an array

and I want to push all state to except some item

so here's my state

state = {
    username: '..',
    date: '..',
    time: '..',
    description: '..',
    images: '..',
    buildingNumber: '..',
    status: '..',
    serviceDB: '..',
    snapshotKey: '..', // i don't need this when pushed
    count: -1, // i don't need this when pushed
  };

here's my code

 let order = [];
    order.push(this.state);
    console.log(order); it's log all state 

// I want to push it to DB
    database()
      .ref(`Providers/ProvidersOrders/${uid}`)
      .push(...order);
  };

Upvotes: 3

Views: 148

Answers (3)

Yoel
Yoel

Reputation: 7965

You can use Destructuring assignment As shown in the documentation

const {  count,snapshotKey, ...newData } = this.state;

Now, newData contains:

 newData={
    username: '..',
    date: '..',
    time: '..',
    description: '..',
    images: '..',
    buildingNumber: '..',
    status: '..',
    serviceDB: '..',
  };

now use in newData

 database()
      .ref(`Providers/ProvidersOrders/${uid}`)
      .push(...newData);

You can read more about it here and here also here plus great examples

Upvotes: 0

Danziger
Danziger

Reputation: 21161

You can use a destructuring assignment and the rest parameters syntax if you want to do it without using any library:

const { snapshotKey, count, ...rest } = this.state;

...

order.push(rest);

Otherwise, you can also use Lodash's _.omit function:

order.push(_.omit(this.state, ['snapshotKey', 'count']));

Alternatively, if you want to select which properties to use, you can use destructuring again and shorthand property names to create the object:

const {
    username,
    date,
    time,
    description,
    images,
    buildingNumber,
    status,
    serviceDB,
} = this.state;

...

order.push({
    username,
    date,
    time,
    description,
    images,
    buildingNumber,
    status,
    serviceDB,
});

Or, with Lodash, use _.pick, which is the opposite of _.omit:

order.push(_.pick(this.state, [
    'username',
    'date',
    'time',
    'description',
    'buildingNumber',
    'status',
    'serviceDB',
]));

Upvotes: 1

StepUp
StepUp

Reputation: 38094

If you want to select some properties then just declare properties that you want:

let {snapshotKey, count, ...y} = state;
arr.push(y);    

An example:

state = {
    username: '1',
    date: '2',
    time: '3',
    description: '4',
    images: '5',
    buildingNumber: '6',
    status: '7',
    serviceDB: '8',
    snapshotKey: '9', // i don't need this when pushed
    count: -10, // i don't need this when pushed
  };
let arr = [];
let {snapshotKey, count, ...y} = state;
arr.push(y);
console.log(arr);

Upvotes: 0

Related Questions