How can I remove duplicates in an array of object? - javascript

I have an array which looks like this :
var array =
[
{
key : { id : 1 , pack : "pack 1"},
values : [
{
item : { id : 1 , name : "item1"},
itemP : {id : 2 , name : "itemP12"}
},
{
item : { id : 4 , name : "item4"},
itemP : {id : 2 , name : "itemP12"}
},
]
}
]
I want to remove duplicate itemP so with a function it will look like this :
var array =
[
{
key : { id : 1 , pack : "pack 1"},
values : [
{
item : { id : 1 , name : "item1"},
itemP : {id : 2 , name : "itemP12"}
},
{
item : { id : 4 , name : "item4"},
itemP : null
},
]
}
]
When I try I always have errors. It is possible to do this?
Update
I try to do this :
console.log(array.map(pack =>
pack.values.map((item) => {
var test = JSON.stringify(item)
var set = new Set(test)
return Array.from(set).map((item)=> JSON.parse(item))
}
)
))
Unexpected end of JSON input
I also try something will filter but it doesn't work:
console.log(this.package.map(pack => pack.values.filter(
(value, index , array) => array.itemP.indexOf(value) === index
)))

Instead of mapping every key property, I suggest cloning the whole structure and setting the object value as null in the cloned one, avoiding unintentionally mutating the original structure.
function nullifyDupes(array) {
const clone = JSON.parse(JSON.stringify(array));
const seen = {};
clone.forEach(pack => {
pack.values.forEach(items => {
for (const item in items) {
const id = items[item].id;
if (seen[id]) items[item] = null;
else seen[id] = true;
}
});
});
return clone;
}
const originalArray = [{
key : { id : 1 , pack : "pack 1"},
values : [{
item : { id : 1 , name : "item1"},
itemP : {id : 2 , name : "itemP12"}
},
{
item : { id : 4 , name : "item4"},
itemP : {id : 2 , name : "itemP12"}
}]
}];
const mutatedArray = nullifyDupes(originalArray);
console.log(mutatedArray);

To achieve expected result, use below option of using map
Loop array using map
Use nameArr to check duplicate and assigning null value
Loop values array and check the name in nameArr using indexOf and assign null
var array = [
{
key : { id : 1 , pack : "pack 1"},
values : [
{
item : { id : 1 , name : "item1"},
itemP : {id : 2 , name : "itemP12"}
},
{
item : { id : 4 , name : "item4"},
itemP : {id : 2 , name : "itemP12"}
}
]
}
]
console.log(array.map(v => {
let nameArr = []
v.values = v.values.map(val => {
if(nameArr.indexOf(val.itemP.name) !== -1){
val.itemP.name = null
}else{
nameArr.push(val.itemP.name)
}
return val
})
return v
}))

You can use map and an object to check if its already exist. Like
var obj = {}
and loop over values
var values = [
{
item : { id : 1 , name : "item1"},
itemP : {id : 2 , name : "itemP12"}
},
{
item : { id : 4 , name : "item4"},
itemP : {id : 2 , name : "itemP12"}
}
]
values.map((v) => {
if(!obj[v.itemP.id + '-' + v.itemP.name]) {
obj[v.itemP.id + '-' + v.itemP.name] = true;
return v;
}
return { item : v.item }
})

You can map your array elements to array objects which don't include your duplicates using .map(). For each iteration of .map() you can again use .map() for your inner values array to convert it into an array of objects such that the duplicates are converted to null. Here I have kept a seen object which keeps track of the properties seen and their stringified values. By looping over all the properties in your object (using for...of), you can work out whether or not the key-value pair has been seen before by using the seen object.
The advantage of this approach is that it doesn't just work with one property (ie not just itemP), but it will work with any other duplicating key-value pairs.
See example below:
const array = [{key:{id:1,pack:"pack 1"},values:[{item:{id:1,name:"item1"},itemP:{id:2,name:"itemP12"}},{item:{id:4,name:"item4"},itemP:{id:2,name:"itemP12"}}]}];
const seen = {};
const res = array.map(obj => {
obj.values = obj.values.map(vobj => {
for (let p in vobj) {
vobj[p] = seen[p] === JSON.stringify(vobj[p]) ? null : vobj[p];
seen[p] = seen[p] || JSON.stringify(vobj[p]);
}
return vobj;
});
return obj;
});
console.log(res);
For an approach which just removed itemP from all object in accross your array you can use:
const array = [{key:{id:1,pack:"pack 1"},values:[{item:{id:1,name:"item1"},itemP:{id:2,name:"itemP12"}},{item:{id:4,name:"item4"},itemP:{id:2,name:"itemP12"}}]}];
let itemP = "";
const res = array.map(obj => {
obj.values = obj.values.map(vobj => {
vobj.itemP = itemP ? null : vobj.itemP;
if('itemP' in vobj) {
itemP = itemP || JSON.stringify(vobj.itemP);
}
return vobj;
});
return obj;
});
console.log(res);

Related

How to create a sub-associative object from a list of array keys in JavaScript?

I have an object from user input. The keys to that object are separated by commas, and I just want to separate those keys and make the keys of the object.
The key_array below is dynamic from user input, generates a different array each time, below I give you an example.
I have shown the object in my code which you can see below. you can also see the output by running that code.
var main_array = {};
var key_array = {
'user,name' : 'user name',
'user,email' : 'Email address',
'order,id' : 123456,
'order,qty' : 2,
'order,total' : 300,
'order,product,0,name' : "product1",
'order,product,0,qty' : 1,
'order,product,0,price' : 100,
'order,product,1,name' : "product2",
'order,product,1,qty' : 1,
'order,product,1,price' : 200,
};
for (keys in key_array){
var value = key_array[keys];
// What do I do here to get the output I want?
main_array['[' + keys.split(",").join('][')+ ']'] = value;
}
console.log(main_array);
Running the code above will give you the following output which is incorrect. And the output I don't want.
{
[order][id]: 123456,
[order][product][0][name]: "product1",
[order][product][0][price]: 100,
[order][product][0][qty]: 1,
[order][product][1][name]: "product2",
[order][product][1][price]: 200,
[order][product][1][qty]: 1,
[order][qty]: 2,
[order][total]: 300,
[user][email]: "Email address",
[user][name]: "user name"
}
I want an output like JSON below, so please tell me how to do it.
{
"user":{
"email" : "Email address",
"name" : "user name"
},
"order":{
"id" : 123456,
"qty" : 2,
"total" : 300,
"product":[
{
"name" : "product1",
"price" : 100,
"qty" : 1
},{
"name" : "product2",
"price" : 200,
"qty" : 1
}
]
}
}
Note: Please do not use eval, as using eval in this way is terribly unreliable, bad work and unsafe. Because I get all my data from user input, the likelihood of abuse can increase.
Use Object.entries to go over key and values of object.
Split the key by , separator and then build the object.
While building object, make sure to merge the keys and values using mergeTo method.
Then convert the objects which has the numerical keys then convert to object using convertObjsToArray method.
var key_array = {
"user,name": "user name",
"user,email": "Email address",
"order,id": 123456,
"order,qty": 2,
"order,total": 300,
"order,product,0,name": "product1",
"order,product,0,qty": 1,
"order,product,0,price": 100,
"order,product,1,name": "product2",
"order,product,1,qty": 1,
"order,product,1,price": 200
};
const mergeTo = (target, obj) => {
Object.entries(obj).forEach(([key, value]) => {
if (typeof value === "object" && !Array.isArray(value)) {
if (!target[key]) {
target[key] = {};
}
mergeTo(target[key], obj[key]);
} else {
target[key] = value;
}
});
};
const convertObjsToArray = obj => {
Object.entries(obj).forEach(([key, value]) => {
if (typeof value === "object") {
if (Object.keys(value).every(num => Number.isInteger(Number(num)))) {
obj[key] = Object.values(value);
} else {
convertObjsToArray(obj[key]);
}
}
});
};
const res = {};
Object.entries(key_array).map(([key, value]) => {
const keys = key.split(",");
let curr = { [keys.pop()]: value };
while (keys.length > 0) {
curr = { [keys.pop()]: curr };
}
mergeTo(res, curr);
});
convertObjsToArray(res);
console.log(res);
You can create the objects and keys required from the string dynamically, take each key and split it to an array using split(','). Using each item in the array create the structure required. Assuming if a key is a number, then it's parent must be an array.
Object.keys(key_array).forEach(key => {
const path = key.split(',');
let current = main_array;
for (let i = 0; i < path.length - 1; i++) {
if (!current[path[i]]) {
current[path[i]] = path[i + 1] && !isNaN(path[i + 1]) ? [] : {};
}
current = current[path[i]];
}
current[path.pop()] = key_array[key];
});
console.log(main_array); // Desired result

How to add <hr> after every new category

I have a array of object called elements, and the objects have two values (name and category).
[
{name : 'key1', category : 'tech'},
{name : 'key2', category : 'tech'},
{name : 'key3', category : 'tech'},
{name : 'cable1' , category : 'hard'}
{name : 'cable2' , category : 'hard'}
{name : 'cable3' , category : 'hard'}
{name : 'cable4' , category : 'hard'}
]
I want to display all names but add an <hr> whenever reaches a new category
Please help and thank you of helping.
I would first group your objects by category using Array.prototype.reduce(), then iterate over each category using Array.prototype.map():
const data = [
{name : 'key1', category : 'tech'},
{name : 'wire1' , category : 'misc'},
{name : 'key2', category : 'tech'},
{name : 'cable1' , category : 'hard'},
{name : 'key3', category : 'tech'},
{name : 'cable2' , category : 'hard'},
{name : 'wire2' , category : 'misc'}
];
const dataMap = data.reduce((acc, x) => {
acc[x.category] = [...(acc[x.category] || []), x];
return acc;
}, {});
const html = Object.entries(dataMap).map(([cat, items]) => {
return items.map(item => `<div>${item.name} ${item.category}</div>`).join('');
}).join('<hr>');
document.getElementById('app').innerHTML = html;
<div id="app"></div>
You can try something like this,
var category;
$.each(object,function(i,objval)
{
console.log(objval['name']);
if(category != "" && category != objval['category'])
{
console.log("<hr>");
}
category = objval['category'];
});
How about something like:
prev_category = undefined;
elements.forEach(function(e) {
if (i > 0 && e.category != prev_category) {
console.log('<hr>');
}
prev_category = e.category;
console.log(e.name);
});
(of course, you can replace the console.log() commands with whatever you really want to do with those texts, e.g. append them to one big string)
Iterate the object and use template literals to create the dom and check if the index of the array is not same as length then add an hr
let elements = [{
name: 'key',
category: 'tech'
},
{
name: 'cable',
category: 'hard'
}
]
let str = '';
elements.forEach(function(item, index) {
str += `<div class='elem'><span>${item.name}</span><span> ${item.category}</span></div>`
if (index !== elements.length - 1) {
str += `<hr>`
}
});
document.getElementById('container').innerHTML = str
<div id='container'></div>
If you are looking for just border then use css pseudo selector
let elements = [{
name: 'key',
category: 'tech'
},
{
name: 'cable',
category: 'hard'
}
]
let str = '';
elements.forEach(function(item, index) {
str += `<div class='elem'><span>${item.name}</span><span> ${item.category}</span></div>`
});
document.getElementById('container').innerHTML = str
.elem:not(:last-child) {
border-bottom: 1px solid black;
}
<div id='container'></div>
Basically you need to sort the data by category first then, render the element, I use react code as example
const data = [
{
name: "Huawei",
category: "phone"
},
{
name: "Iphone",
category: "phone"
},
{
name: "Refacoring Improving the design of existing code",
category: "book"
},
{
name: "Python Crash Course",
category: "book"
},
{
name: "My heart will go on",
category: "music"
},
{
name: "I'm your angel",
category: "music"
}
];
function generateCom(data) {
let listComps = [];
let category = "";
// sort the data by category
data.sort((a, b) => (a.category > b.category ? 1 : -1));
// generate the component by category
data.forEach((ele, idx) => {
if (idx === 0) {
listComps.push(<h3>{ele.category}</h3>);
listComps.push(<li>{ele.name}</li>);
category = ele.category;
return;
}
if (ele.category === category) {
listComps.push(<li>{ele.name}</li>);
} else {
listComps.push(<hr />);
listComps.push(<h3>{ele.category}</h3>);
listComps.push(<li>{ele.name} </li>);
category = ele.category;
}
});
return listComps;
}
can refer to the example
https://codesandbox.io/embed/6x0p7908qw

Using Underscore restructure the JSON

Original JSON
var dataJson = [{
"MID" : "NTE",
"TNAME" : "gGAR",
"MVALUE" : 6
}, {
"MID" : "NTP",
"TNAME" : "gGAR",
"MVALUE" : 50
}, {
"MID" : "NTR",
"TNAME" : "gGAR",
"MVALUE" : 12
}, {
"MID" : "NTE",
"TNAME" : "gRRR",
"MVALUE" : 1
}, {
"MID" : "NTP",
"TNAME" : "gRRR",
"MVALUE" : 100
}, {
"MID" : "NTR",
"TNAME" : "gRRR",
"MVALUE" : 1
}];
Need to group by "TNAME" and after all the group taking first three objects based on "MID" and modify the JSON structure like
Expected output JSON:
var Convert = [
{
"GGARMVALUENTE":6,
"GGARMVALUENTP":50,
"GGARMVALUENTR":12,
"GRRRMVALUENTE":1,
"GRRRMVALUENTP":100,
"GRRRMVALUENTR":1
}
]
Finally it works according to your requirements. Just Solved Puzzling Question. :)
function restructure (data) {
let convert = []
let buffer = null
let pairs = data.map(d => {
return [`${d.TNAME.toUpperCase()}MVALUE${d.MID}`, d.MVALUE]
})
pairs.forEach((p, i) => {
let name = p.shift()
let value = p.shift()
let pair = {
[name]: value
}
if (buffer && buffer[name]) {
convert.push(buffer)
delete buffer
buffer = pair
} else {
if (buffer) {
Object.assign(buffer, pair)
} else {
buffer = pair
}
if (pairs.length === i + 1) {
convert.push(buffer)
delete buffer
}
}
})
return convert
}
console.log(restructure(dataJson))

How to Combine or Merge Object Array with Object Array Jquery

i have an object like this in my console:
ObjectName1 : Array(3)
0 : { id : 1, name : 'foo' },
1 : { id : 2, name : 'foo-2' },
2 : { id : 3, name : 'foo-3' },
ObjectName2 : Array(3)
0 : { id : 1, foo : 'bar' },
1 : { id : 2, foo-2 : 'bar-2' },
2 : { id : 3, foo-3 : 'bar-3' },
and as usually if we want to get the name, just write : ObjectName1[key].name right ?
now if i want to get the key from ObjectName2 (foo, foo-2, foo-3) how to get the key from ObjectName2 using the value from ObjectName1 ?
i have written like this :
// just say there is an each above this comment
var name = ObjectName1[key].name;
var bar = ObjectName2[key]+"."+name;
// end each
but it just showed
[Object object].foo
[Object object].foo-2
[Object object].foo-3
the output should be like this :
bar
bar-2
bar-3
it is possible doing like i want to do ? help me please if it is possible
any help will be very appreciated.
*note : i'm not sure what is the case name in my problem, so forgive me if the title went wrong
thanks
Try this one. Loop through each object in ObjectName1 object and get the name in appropriate index, this name will be the key for the ObjectName2 object. Then use that key to print the appropriate value from ObjectName2
var ObjectName1 = [{'id' : 1, 'name' : 'foo'}, {'id' : 2, 'name' : 'foo-2'}, {'id' : 3, 'name' : 'foo-3'}];
var ObjectName2 = [{'id' : 1, 'foo' : 'bar'}, {'id' : 2, 'foo-2' : 'bar-2'}, {'id' : 3, 'foo-3' : 'bar-3'}];
for(var i = 0; i < ObjectName2.length; i++){
console.log(ObjectName2[i][ObjectName1[i]['name']]);
}
Something like this?
var name = ObjectName1[key].name;
ObjectName2.forEach(function(a) {
if (a.keys().includes(name)) {
var bar = a[name];
// then do what you want with bar
}
}
As commented, your key is an object. Hence, it is showing [Object object].foo-3.
You will have to use 2 loops and check if the key is inside current object. If yes, print it, else continue.
var ObjectName1 =[
{ id : 1, name : 'foo' },
{ id : 2, name : 'foo-2' },
{ id : 3, name : 'foo-3' },
]
var ObjectName2 = [
{ id : 1, foo : 'bar' },
{ id : 2, 'foo-2' : 'bar-2' },
{ id : 3, 'foo-3' : 'bar-3' },
];
ObjectName1.forEach(function(obj){
ObjectName2.forEach(function(obj2){
var key = obj.name;
if(key in obj2){
console.log(obj2[key])
}
})
})
now if i want to get the key from ObjectName2 (foo, foo-2, foo-3) how to get the key from ObjectName2 using the value from ObjectName1 ?
If you know those are parallel arrays (where [0] in one array is intentionally a match for [0] in the other array), you can simply loop through:
ObjectName1.forEach(function(entry1, index) {
var value = ObjectName2[index][entry1.name];
console.log(entry1.name + " = " + value);
});
Example:
var ObjectName1 = [
{ id : 1, name : 'foo' },
{ id : 2, name : 'foo-2' },
{ id : 3, name : 'foo-3' }
];
var ObjectName2 = [
{ id : 1, "foo" : 'bar' },
{ id : 2, "foo-2" : 'bar-2' },
{ id : 3, "foo-3" : 'bar-3' }
];
ObjectName1.forEach(function(entry1, index) {
var value = ObjectName2[index][entry1.name];
console.log(entry1.name + " = " + value);
});
That assumes you know they're parallel arrays.
If not, you have to search for it. Array.prototype.findIndex will return the index of the first element where a callback returns true:
ObjectName1.forEach(function(entry1) {
console.log("entry1.name = " + entry1.name);
var index = ObjectName2.findIndex(function(entry2) {
// See if entry2 contains a key with that value
return entry1.name in entry2;
});
console.log(index == -1 ? "Not found" : ("Found at index #" + index + ", value = " + ObjectName2[index][entry1.name]));
});
Example:
var ObjectName1 = [
{ id : 1, name : 'foo' },
{ id : 2, name : 'foo-2' },
{ id : 3, name : 'foo-3' }
];
var ObjectName2 = [
{ id : 1, "foo" : 'bar' },
{ id : 2, "foo-2" : 'bar-2' },
{ id : 3, "foo-3" : 'bar-3' }
];
ObjectName1.forEach(function(entry1) {
console.log("entry1.name = " + entry1.name);
var index = ObjectName2.findIndex(function(entry2) {
// See if entry2 contains a key with that value
return entry1.name in entry2;
});
console.log(index == -1 ? "Not found" : ("Found at index #" + index + ", value = " + ObjectName2[index][entry1.name]));
});
If you don't really need the key (e.g., index) of the matching object in ObjectName2, just the object, use find instead:
ObjectName1.forEach(function(entry1) {
console.log("entry1.name = " + entry1.name);
var entry = ObjectName2.find(function(entry2) {
// See if entry2 contains a key with that value
return entry1.name in entry2;
});
console.log(!entry ? "Not found" : ("Found, value is " + entry[entry1.name]));
});
Example:
var ObjectName1 = [
{ id : 1, name : 'foo' },
{ id : 2, name : 'foo-2' },
{ id : 3, name : 'foo-3' }
];
var ObjectName2 = [
{ id : 1, "foo" : 'bar' },
{ id : 2, "foo-2" : 'bar-2' },
{ id : 3, "foo-3" : 'bar-3' }
];
ObjectName1.forEach(function(entry1) {
console.log("entry1.name = " + entry1.name);
var entry = ObjectName2.find(function(entry2) {
// See if entry2 contains a key with that value
return entry1.name in entry2;
});
console.log(!entry ? "Not found" : ("Found, value is " + entry[entry1.name]));
});

how to check object name?

I have object and this object include objects too. It looks like:
$scope.data = {
tree : {
name : 'oak',
old : 54
},
dog : {
name : 'Lucky',
old : 3
},
system1 : {
name : '',
old : ''
},
baby : {
name : 'Jack',
old : 1
},
cat : {
name : 'Fluffy',
old : 2
},
system2 : {
name : '-',
old : '-'
}
}
As you can see this objects has obj name like - tree, dog, system etc. And I want to take only objects with name system, but this name can changes like system1, system123, system8. So I try to use this reg exp for ignore numbers
replace(/\d+/g, '')
But I can't reach this object name. I try this:
angular.forEach($scope.data, function(item){conole.log(item)}) // but it shows content in obj not obj name..
How can I reach this obj name and distinguish this 2 system objects?
var data = {
tree : {
name : 'oak',
old : 54
},
dog : {
name : 'Lucky',
old : 3
},
system1 : {
name : '',
old : ''
},
baby : {
name : 'Jack',
old : 1
},
cat : {
name : 'Fluffy',
old : 2
},
system2 : {
name : '-',
old : '-'
}
}
data = Object.keys(data) // get keys
.filter(key => key.startsWith('system')) // filter keys starting with system
.map(key => data[key]) // map to the values, returning a new array
console.log(data) // and you have you array with systems
Pass another param to the function like key to the forEach callBack Function. It is the key of the each object inside the object in your use-case.
Check the below example
var items = {
car: {
a: 123
},
dog: {
b: 234
},
system: {
c: 456
}
};
angular.forEach(items, function(item, key) {
console.log(key);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
You can use Object.keys(myObject), that return an array of all the keys of the passed object, for istance:
var myObject= {
cat : {
name : 'Fluffy',
old : 2
},
system2 : {
name : '-',
old : '-'
}
}
var keys = Object.keys(myObject); // Keys will be ['cat', 'system2']
Cheers
You have to pass another parameter to angular foreach function to get the key name of the object like this:-
angular.forEach($scope.data, function(item, key){ // Here key is the keyname of the object
console.log(item, key);
});

Categories