Home > database >  Set value is object
Set value is object

Time:09-05

I want to put obj into value ex. <option value={valueSort}>// valueSort = {name: 'ASC'} for use to sort by name in my project but now the result that is [object Object]. I don't know what is mean

react file a.tsx

import { useState } from 'react';

const a = () => {
const [filterType, setFilterType] = useState('');

const valueSort = {
nameASC:{ name: "ASC" },
nameDESC:{ name: "DESC" },
}

return (
<select
 onChange={(e) => {
  setFilterType(e.target.value);
  }}
>
  <option value={valueSort.nameASC}>By A - Z</option>
  <option value={valueSort.nameDESC}>By Z - A</option>
</select>
)}
export default a

controller file a.controller.ts

@Get('/')
async page(@Query() query: PaginateDto) {
const { sort } = query;
console.log('controller = '   sort);
const sortby: any = sort;
return await this.aService.find(sortby);

service file a.service.ts

find(sort) {
 console.log('service = ' sort);
 return this.aModel.find().sort(sort).exec();
}

now the result in console log is

controller = [object Object]
service = [object Object]

I want the output in finally is

controller = { name: "ASC" }
service = { name: "ASC" }

for use sort by name

CodePudding user response:

You are defining you sort options like this:

const valueSort = {
 nameASC: { name: "ASC" }, 
 nameDESC: { name: "DESC" },
}

This means, that when you are using valueSort.nameASC OR valueSort.nameDESC you are actually using an object.

When trying to add a value <option value={valueSort.nameASC}> you are trying to assign an object and that doesn't work (not directly).

It's not clear why you are trying to use an object and not a string. But if you still need to use an object, then you need to serialize that. The simplest way would be to use JSON.stringify. Something similar to this:

  <option value={JSON.stringify(valueSort.nameASC)}>By A - Z</option>
  <option value={JSON.stringify(valueSort.nameDESC)}>By Z - A</option>

Then use JSON.parse anywhere before being able to use these values.

  • Related