javascript - React & Axios - 为对象动态添加键和值
问题描述
在我的一个小项目上工作并遇到了一个问题。我正在使用“ASOS”API,我需要动态地将键和值添加到查找正确产品所需的参数中。例如选择颜色、尺寸、价格范围等。问题是,我尝试过的所有事情都没有成功。
如何为对象动态添加键和值?
像这样的东西:
currency: "USD",
sizeSchema: "US",
lang: "en-US",
newKey: newValue
这是我的代码:
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>
);
};
谢谢!
请记住
ThefacetKey
和facetValue
返回字符串值,以及用户是否没有选择“方面”或过滤产品的选项。然后就返回undefined
了,当然可以把这个改成null。
解决方案
您可以将[]
运算符与对象一起使用。
一般来说:
let obj = {};
let key = 'x';
let value = 3;
obj[key] = value;
console.log(obj);
console.log(obj[key]);
在您的示例中:
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;
推荐阅读
- function - 分配元素值之前需要初始化吗?
- apache - 在 apache 本地 Web 服务器上实现 reCaptcha
- python - 如何在 pycharm 中保存项目以及在哪里可以找到它们
- python - Flask:如何向可能同时访问的每个用户返回不同的内容
- algorithm - 如何在这个递归解决方案中添加记忆来拼写单词
- java - 如何使用从微调器中选择的项目
- java - 在 android [JAVA] 中的多个 Arraylist 中添加 JSONarrays
- c# - 如何根据 xml 文件数据添加 GMap 标记?
- python - 无法更改 python 字符串
- javascript - driver.manage(...).window(...).getSize 不是 selenium 中的函数