Reputation: 7755
I wanted to show only a single item if it has the same it has same contact_id
and id
.
Expected output is Name: Robert Williams, Name: John Jones
RESPONSE
{
"id": "8888",
"contact_id": "3424",
"contact_name": "Robert Williams",
},
{
"id": "9999",
"contact_id": "4343",
"contact_name": "John Jones",
},
{
"id": "8888",
"contact_id": "3424",
"contact_name": "Robert Williams",
}
CODE
{
data.map((item, index) => {
return (
<div key={index}>
<h1>Name</h1>
<p>
{item.contact_name}
</p>
</div>
);
});
}
Upvotes: 1
Views: 103
Reputation: 13078
You can use Array.prototype.reduce():
const dataTransformed = data.reduce((arr, curr) => {
return arr.find(
item => item.id === curr.id && item.contact_id === curr.contact_id
)
? [...arr]
: [...arr, curr];
}, []);
Then iterate over the transformed array
Upvotes: 1
Reputation: 797
Create an object and a filter function:
const memo = {};
const filter = (item) => {
if(!memo[item.id]){
return true;
}else {
memo[item.id] = item.id;
return false;
}
}
Then in your render:
{
data.filter(filter).map((item, index) => {
return (
<div key={index}>
<h1>Name</h1>
<p>
{item.contact_name}
</p>
</div>);
});
}
Upvotes: 0
Reputation: 28654
Something like this?
let data = [{
"id": "8888",
"contact_id": "3424",
"contact_name": "Robert Williams",
},
{
"id": "9999",
"contact_id": "4343",
"contact_name": "John Jones",
},
{
"id": "8888",
"contact_id": "3424",
"contact_name": "Robert Williams",
}
];
let transform = (data) => {
let existing = {};
let result = [];
data.forEach(x => {
if (!existing[x.id] || !existing[x.id][x.contact_id]) {
existing[x.id] = {
[x.contact_id]: true
};
result.push(x);
}
});
return result;
}
console.log(transform(data));
Now you can render result returned by above function.
Upvotes: 1
Reputation: 1544
One liner ES6 can do the magic:
const arr = [{
"id": "8888",
"contact_id": "3424",
"contact_name": "Robert Williams",
},
{
"id": "9999",
"contact_id": "4343",
"contact_name": "John Jones",
},
{
"id": "8888",
"contact_id": "3424",
"contact_name": "Robert Williams",
}]
const data = arr.filter((v,i,a)=>a.findIndex(t=>(t.id === v.id && t.contact_id===v.contact_id))===i)
and then
{
data.map((item, index) => {
return (
<div key={index}>
<h1>Name</h1>
<p>
{item.contact_name}
</p>
</div>
);
});
}
Upvotes: 2
Reputation: 514
Here is a solution:
{
data.map((item, index) => {
if(item.contact_name === item.contact_id) {
return (
<div key={index}>
<h1>Name</h1>
<p>
{item.contact_name}
</p>
</div>
);
} else {
return null;
}
});
}
Upvotes: -1