Removing duplicates from an array of objects - javascript

I have an object which has json objects called
mainobject =
Array[2]
>0: object
>Innerobject1 : Array[2]
>0 : object
Name : "Xavier"
Dup : "B"
>1 : object
Name : "Gh"
Dup : "B"
>1: object
>Innerobject2 : Array[2]
>0 : object
Name : "Cat"
Dup : "C"
>1 : object
Name : "Dog"
Dup : "D"
I need to make the "dup" as "" which was already present in the first object if any .My expected output is:
Array[2]
>0: object
>Innerobject1 : Array[2]
>0 : object
Name : "Xavier"
Dup : "B"
>1 : object
Name : "Gh"
Dup : ""
>1: object
>Innerobject2 : Array[2]
>0 : object
Name : "Cat"
Dup : "C"
>1 : object
Name : "Dog"
Dup : "D"
Edit:
The object in json format:
:
"[{"Innerobject1":[{"Name" :"Xavier","Dup":"B"},{"Name" :"Gh","Dup":"B"}]},
{"Innerobject2":[{"Name" : "Cat","Dup":"C"},{"Name":"Dog", "Dup":"D"}]}]"

I'm not quite sure that I have interpreted your posted array of objects correct. But you can do something like this:
Iterate over the array and store the key you want to be unique in an object. When encountered more then once set the new value to an empty string:
var seen = {};
mainobject.forEach(function(obj) {
if (seen[obj.Name]) {
obj.Name = "";
}
seen[obj.Name] = true;
});
You might need multiply iterations, dependents on how many nested arrays you got:
var seen = {};
mainobject.forEach(function(inner_arr) {
inner_arr.forEach(function(obj) {
if (seen[obj.Name]) {
obj.Name = "";
}
seen[obj.Name] = true;
});
});

The solution using Array.forEach and Object.keys functions:
var mainobject = JSON.parse('[{"Innerobject1":[{"Name" :"Xavier","Dup":"B"},{"Name" :"Gh","Dup":"B"}]},{"Innerobject2":[{"Name" : "Cat","Dup":"C"},{"Name":"Dog", "Dup":"D"}]}]');
mainobject.forEach(function(obj){
Object.keys(obj).forEach(function(k){
obj[k].forEach(function(o){
if (this["Dup"]) {
(this["Dup"].indexOf(o["Dup"]) !== -1)? o["Dup"] = "" : this["Dup"].push(o["Dup"]);
} else {
this["Dup"] = [o["Dup"]];
}
})
});
}, {});
console.log(JSON.stringify(mainobject, 0, 4));
The console.log output:
[
{
"Innerobject1": [
{
"Name": "Xavier",
"Dup": "B"
},
{
"Name": "Gh",
"Dup": ""
}
]
},
{
"Innerobject2": [
{
"Name": "Cat",
"Dup": "C"
},
{
"Name": "Dog",
"Dup": "D"
}
]
}
]

Related

How to get key of multiple keys in json array and manipulate their data?

I want to fetch the nested key and manipulates their data.
I have tried 2 methods:
Example 1:
for (let key in the dictionary) {
for (let keys in dictionary[key]) {
console.log(keys)
}
}
Example 2:
for (let key in dictionary) {
for (let k in lng.dictionary[key]["data"]) {
console.log(k)
}
}
In Example 1, I am getting both the keys name and data.
In Example 2,I am getting only a, b, c, d, yes, no, f, hgs, cft, vit. not
their values.
But I want to:
Fetch only data.
and manipulate their values like {"key":"a","value":"some text"},{"key":"b","value":"some text"},{"key":"c","value":"c for"},{},{}.
here is my Json object
"dictionary" : {
"bar" : {
"name" : "Bar",
"data" : {
"a" : "some text",
"b" : "some text",
"c" : "c for",
"d" : "some text",
"yes" : "true",
"No" : "true",
"f" : "some text"
}
},
"text" : {
"name" : "Text",
"data" : {
"hgs" : "some text",
"cft" : "some text",
"vit" : "some text"
}
}
}
You can use Object.values to extract the inner data object and for each key and value of the data object which can be iterated by Object.entries we would form a temp object.
Using Array.reduce we can accumulate the temp objects into an array.
const data = {"dictionary":{"bar":{"name":"Bar","data":{"a":"some text","b":"some text","c":"c for","d":"some text","yes":"true","No":"true","f":"some text"}},"text":{"name":"Text","data":{"hgs":"some text","cft":"some text","vit":"some text"}}}};
const dataProcessed = Object.values(data.dictionary).reduce((acc, obj) => {
Object.entries(obj.data).forEach(([key, value])=>{
temp = {};
temp["key"] = key;
temp["value"] = value;
acc.push(temp);
});
return acc;
}, []);
console.log(dataProcessed);

Rename JSON Keys based on first "row" in object array

I have a JSON object array where I need to rename the keys based on values in the first object. Trying to do this in NodeJS but not having any luck.
I could probably brute force it with a couple of loops but was hoping for a more scalable solution since the number of "columns" change from time to time.
Here is an example
[{"A" : "Key1", "B" : "Key2", "C" : "Key3"},
{"A" : "Data1", "B" : "Data2", "C" : "Data3"},
{"A" : "Data5", "B" : "Data5", "C" : "Data7"}]
I would like the result to be like
[{"Key1" : "Key1", "Key1" : "Key2", "Key1" : "Key3"},
{"Key1" : "Data1", "Key2" : "Data2", "Key3" : "Data3"},
{"Key1" : "Data5", "Key2" : "Data5", "Key3" : "Data7"}]
let arr = [{"A" : "Key1", "B" : "Key2", "C" : "Key3"},
{"A" : "Data1", "B" : "Data2", "C" : "Data3"},
{"A" : "Data5", "B" : "Data5", "C" : "Data7"}];
const keys = Object.keys(arr[0]).map(i => arr[0][i]);
let result = arr.map(obj => {
const replacedObj = {};
const oriKeys = Object.keys(obj);
for (let i = 0; i < keys.length; i++) {
replacedObj[keys[i]] = obj[oriKeys[i]]
};
return replacedObj;
});
console.log(JSON.stringify(result));
Using Object.entries() with some creative mapping, reducing, destructuring and spreading:
o = i.map(x => Object.entries(x).reduce((a, [k, v]) => ({...a, [i[0][k]]: v}), {}));
Complete snippet:
let input, output;
input = [
{"A" : "Key1", "B" : "Key2", "C" : "Key3"},
{"A" : "Data1", "B" : "Data2", "C" : "Data3"},
{"A" : "Data5", "B" : "Data5", "C" : "Data7"}
];
output = input.map(x => Object.entries(x).reduce((a, [k, v]) => ({...a, [input[0][k]]: v}), {}));
console.log(output);
Lets say the old array is stored in a var called oldArray:
var keys = Object.keys(oldArray[0]); // get first object keys
var newArray = oldArray.map(function(obj,index){
// Iterate over each object to replace keys
if(index === 0) return obj; /* if first object we dont need to replace
keys */
var objKeys = Object.keys(obj); //old keys for reference only
return Object assign({},{
[keys[0]]: obj[objKeys[0], // assigning first object keys with
current
[keys[1]]: obj[objKeys[1], // object values
[keys[2]]: obj[objKeys[3],
});
});
console.log(newArray);
/* You also can change the key value asignation with a for, so you
can handle not only 3 key values object, this could be optimized
with es6 ans spread operator definition but rather to implement it in
es5 for less complexity */

How to push object in array with those records in object should not reside under object name?

I am trying to push data in array but I don't want that data to come under any object.
Expected output:
name : "abc"
array1 : [],
flag : false
myObj1 : {}
myObj2 : {}
But I am getting data in arr variable in array like below:
myObj :
name : "abc"
array1 : [],
flag : false
myObj1 : {}
myObj2 : {}
Code:
var arr = [];
function pushData(myObj)
{
arr.push(
{
myObj
myObj1 : { title: myObj.name, flag: true, value: 0 },
myObj2: { location : null,age : 10 }
//some other objects which I want to initialize here only
}
);
}
Is this possible to get expected output in arr variable?
I think you want to assign Object1 and 2 to Object:
arr.push(Object.assign({},myObj,{
myObj1 : { title: myObj.name, flag: true, value: 0 },
myObj2: { location : null,age : 10 }
}));
Will create this:
[{
name : "abc"
array1 : [],
flag : false
myObj1 : {title,flag,value}
myObj2 : {location,age}
}];
If you're transpiling your code with Babel for ES6 capabilities, you can use object spread properties:
var arr = [];
function pushData(myObj) {
arr.push({
...myObj,
myObj1: {},
myObj2: {}
});
}
pushData({ name: "abc", array1: [], flag: false });
console.log(arr);
Here's the current compatibility stats.

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);
});

Javascript - Reduce array with multiple-key objects [duplicate]

This question already has answers here:
Group array items using object
(19 answers)
Closed 6 years ago.
I want to modify a Javascript array, so that the elements having the same values for specifies properties merge into one object in a way that the other properties are kept as a comma-separated string, JSON string, or an array. Basically, I want to turn this:
[
{
"language" : "english",
"type" : "a",
"value" : "value1"
},
{
"language" : "english",
"type" : "a",
"value" : "value2"
},
{
"language" : "english",
"type" : "b",
"value" : "value3"
},
{
"language" : "spanish",
"type" : "a",
"value" : "valor1"
}
]
into this:
[
{
"language" : "english",
"type" : "a",
"value" : ["value1" , "value2"] // A Json string is welcome too
},
{
"language" : "english",
"type" : "b",
"value" : "value3"
},
{
"language" : "spanish",
"type" : "a",
"value" : "valor1"
}
]
I have tried iterating and filtering, then upserted the object as given in the snippet. But I wonder if there is a more elegant way to do that.
P.S EcmaScript6 and additional JS library suggestions are also welcome.
var originalArray = [
{
"language" : "english",
"type" : "a",
"value" : "value1"
},
{
"language" : "english",
"type" : "a",
"value" : "value2"
},
{
"language" : "english",
"type" : "b",
"value" : "value3"
},
{
"language" : "spanish",
"type" : "a",
"value" : "valor1"
}
];
var resultingArray = [];
// iterate through the original array
$.each(originalArray, function(i, val) {
// apply filter on key properties (i.e. language and type)
var result = resultingArray.filter(function( obj ) {
return (obj.language === val.language && obj.type === val.type);
});
// if a record exists, update its value
if (result.length === 1) {
result[0].value += (", " + val.value);
}
// else, add value
else if (result.length === 0) {
resultingArray.push(val);
}
// if multiple rows exist with same key property values...
else {
alert("Too many records with language '" + val.language + "' and type '" + val.type + "'");
}
});
console.log(JSON.stringify(resultingArray));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
This is what you need?
var baseData= [
{
"language" : "english",
"type" : "a",
"value" : "value1"
},
{
"language" : "english",
"type" : "a",
"value" : "value2"
},
{
"language" : "english",
"type" : "b",
"value" : "value3"
},
{
"language" : "spanish",
"type" : "a",
"value" : "valor1"
}
];
var newData = [];
baseData.forEach(function(item, index) {
if (newData.length === 0) {
newData.push(item);
} else {
var dIndex = -1;
newData.forEach(function(itm, idx) {
if (item.language === itm.language && item.type === itm.type) dIndex = idx;
});
if (dIndex !== -1) {
var oldValue = newData[dIndex].value;
if (typeof(oldValue).toString() === 'string') {
newData[dIndex].value = [oldValue, item.value];
}
} else {
newData.push(item);
}
}
});
console.log(newData);

Categories