I'm trying to concatenate values from "seller" Key in a new variables "sellerList" but I'm not achieving to find a good solution.
const data = {
page: {},
product: {
attributes: {
condition: 'used',
offer: {
offer1: {
condition: 'used',
offerID: '1111',
seller: 'Ben',
sellerID: 'abc',
},
offer2: {
condition: 'used',
offerID: '2222',
seller: 'manu',
sellerID: 'def',
},
offer3: {
condition: 'used',
offerID: '3333',
seller: 'Ben',
sellerID: 'abc',
},
},
},
},
};
I found this post which has a similar issue, but it's not working on my side
As we can't use map method on object, I pushed my object into an array like this:
dataArr = [];
dataArr.push(data);
Then I used the following code to concatenate:
const sellersList = Object.keys(digitalData)
.map((o) => o.seller)
.join(';');
console.log('Offer list :' sellersList);
But this returns an empty string: "Offer list :;"
So my goal is to have a final string like this : "ben;manu;ben"
Does anyone have an idea how to arrange the code fit with my case ? Thank you for your help and your time.
CodePudding user response:
You can do it like this. It does rely on your data having this specific shape with those precise key names - but it's not clear what else you can do as I don't know the details of where your data comes from and what else it might look like. Hope this helps give you a start, anyway!
const data = {
page: {},
product: {
attributes: {
condition: "used",
offer: {
offer1: {
condition: "used",
offerID: "1111",
seller: "Ben",
sellerID: "abc",
},
offer2: {
condition: "used",
offerID: "2222",
seller: "manu",
sellerID: "def",
},
offer3: {
condition: "used",
offerID: "3333",
seller: "Ben",
sellerID: "abc",
},
},
},
},
};
const result = Object.values(data.product.attributes.offer).map(offer => offer.seller).join(";");
console.log(result);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Based on the data shape that you shared, you can do it like that:
Object.values(data.product.attributes.offer)
.map(offer => offer.seller)
.join(';')