Reputation: 645
I have a dummy api response consisting of a results array which has objects in it. When I try to map over this array and try to access each individual's object's properties inside another object I'm creating, it throws an error. Any idea what could be wrong?
here's a code snippet
import { result } from "./partnership_rewards_response.json";
result.map((partner,index)=>{
const obj = {
partner.name,
partner.class
}
})
and this is how my json file looks like
{
"result":[obj1, obj2, ...]
}
and the error I'm getting is Parsing error: Unexpected token, expected ","
EDIT: I forgot to specify, I'm trying to populate content in react using useState. so object structure is already initialized in the default value
EDIT2: here's How I'm trying to populate it
const [showModal, setModal] = useState(false);
const [modalContent, setModalContent] = useState({
partner_name: "",
coupon_image:"",
coupon_code : "",
coupon_content:"",
terms:"",
redemption_steps:"",
});
setModalContent(
{
partner.partner_logo,
partner.coupon_image
}
)
Upvotes: 0
Views: 745
Reputation: 1075785
The problem is that you're trying to use shorthand property notation in your object literal, but you can only do that when the source of the property value is a simple identifier like example
, not a property expression like person.name
. When the source of the value isn't just a simple identifier, you have to use the "old" (pre-ES2015) full property syntax (name: value
) instead.
You need to give the property name explicitly:
result.map((partner,index)=>{
const obj = {
name: partner.name,
class: partner.class,
};
// ...I assume there's more here...
})
or re your edit (confusing that you've changed property names):
setModalContent({
partner_logo: partner.partner_logo,
image: partner.image,
});
You could also do it with destructuring and property shorthand notation:
result.map(({name, class},index)=>{
const obj = {
name,
class,
};
// ...I assume there's more here...
})
or re your edit, if you've destructured person
, you could do:
setModalContent({
partner_logo,
image,
});
Upvotes: 2
Reputation: 551
your shorthand syntax is wrong change your code to this
result.map((partner,index) => {
const obj = {
name : partner.name,
class : partner.class
}
})
This should work
Upvotes: 1
Reputation: 5853
Shorthand objects syntax doesn't work because you have dots in the key names.
You can change it to something like:
import { result } from "./partnership_rewards_response.json";
result.map((partner,index)=>{
const obj = {
partnerName: partner.name,
partnerClass: partner.class
}
})
Upvotes: 1