在做我的一个小项目时遇到了一个问题。 我正在使用“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>
);
};
谢谢!
牢记
facetKey
和 facetValue
返回字符串值,如果用户尚未选择“facet”或过滤产品的选项。然后返回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;
关于javascript - React 和 Axios - 动态向对象添加键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67623762/