简体   繁体   中英

React & Axios - Dynamically add key and value to object

Working on a little project of mine and ran into an issue. I am using the "ASOS" API and I need to dynamically add key and value to the parameters that it needs to find the correct product. It is to pick for example color, size, price range etc. Issue is, all things I've tried haven't ended up in a success.

How do I dynamically add key and value to an object?

Something like this:

currency: "USD",
sizeSchema: "US",
lang: "en-US",
newKey: newValue

Here is my code:

const FetchAPI = (props) => {
  const [product, setProducts] = useState([]);
  // Key and Value
  let facetKey = props.facetKey;
  let facetValue = props.facetValue;

// Sets the paramaters
  let params = {
    store: "US",
    offset: props.offset,
    categoryId: props.categoryId,
    limit: props.limit,
    country: "US",
    sort: "freshness",
    currency: "USD",
    sizeSchema: "US",
    lang: "en-US",
  };
  // Need to add my "facetKey" and "facetValue" to "params".

  useEffect(() => {
    const options = {
      method: "GET",
      url: "https://asos2.p.rapidapi.com/products/v2/list",
      params: params,
      headers: {
        "x-rapidapi-key": "",
        "x-rapidapi-host": "",
      },
    };

    axios
      .request(options)
      .then(function (response) {
        setProducts(response.data.products);
        props.items(response.data.itemCount);
        props.facets(response.data.facets);
        console.log(response.data.facets);
      })
      .catch(function (error) {
        console.error(error);
      });
  }, [props.offset, props.limit]);

  return (
    <div>
      <div className={classes.container}>
        {product.map((product) => (
          <ProductCard
            key={product.id}
            img={product.imageUrl}
            name={product.name}
            price={product.price.current.text}
          />
        ))}
      </div>
    </div>
  );
};

Thanks!

Keep in mind The facetKey and facetValue return string values, and if the user havent picked a "facet", or an option to filter the products. Then it returns undefined , can of course change this to null.

You can use the [] operator with objects.

In general:

 let obj = {}; let key = 'x'; let value = 3; obj[key] = value; console.log(obj); console.log(obj[key]);

In your example:

let facetKey = props.facetKey;
let facetValue = props.facetValue;

// Sets the paramaters
let params = {
  // ...
};
// Need to add my "facetKey" and "facetValue" to "params".

if (facetKey)
  params[facetKey] = facetValue;

You can write the code as follows.

let params = {
    store: "US",
    offset: props.offset,
    categoryId: props.categoryId,
    limit: props.limit,
    country: "US",
    sort: "freshness",
    currency: "USD",
    sizeSchema: "US",
    lang: "en-US",
    [facetKey]: facetValue
};

And if facetKey can be undefined, you can do like this.

let params = {
    store: "US",
    offset: props.offset,
    categoryId: props.categoryId,
    limit: props.limit,
    country: "US",
    sort: "freshness",
    currency: "USD",
    sizeSchema: "US",
    lang: "en-US",
};

facetKey && params = { ...params, [facetKey]: facetValue }
// or
if (facetKey) {
    params = { ...params, [facetKey]: facetValue }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM