Comparing 2 objects and making alterations based on Match - javascript

I have 2 objects with key-value pairs that should always be identical (match) otherwise I want to modify the value of the key in object #1 to "Some Value - Not available"
Here are my 2 objects:
Object #1
[
{
"name": "John",
"age": "12",
"id": 1
},
{
"name": "tina",
"age": "19",
"id": 2
}]
Object #2 ( name checker)
[
{
"value": "tina"
},
{
"value": "Trevor"
},
{
"value": "Donald"
},
{
"value": "Elon"
},
{
"value": "Pamela"
},
{
"value": "Chris"
},
{
"value": "Jackson"
}
]
I would like to find out if name in Object #1 is found in Object #2 and if it is not found, add " - not available"
e.i
[
{
"name": "John - not available",
"age": "12",
"id": 1
},
{
"name": "tina",
"age": "19",
"id": 2
}
]
Important Note: I'm using ES5 --- not ES6

This should work in ES5
object1.forEach(function(person) {
var found = false;
Object.keys(object2).forEach(function(key) {
if (person.name === object2[key].value) {
found = true;
}
});
if (!found) {
person.name = person.name + " - not available";
}
});

Related

parse nested JSON Data [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 4 years ago.
I'm new to Javascript, ES6 , and i have hit the wall with this problem
This is the JSON that i'm getting from a webservice
{
"products": [
{
"id": 2,
"id_default_image": "21",
"price": "35.900000",
"name": [
{
"id": "1",
"value": "item 1"
},
{
"id": "2",
"value": "item 1 alternate name"
}
]
},
{
"id": 4,
"id_default_image": "4",
"price": "29.000000",
"name": [
{
"id": "1",
"value": "item 2"
},
{
"id": "2",
"value": "item 2 alternate name"
}
]
}
]
}
The name property in the above JSON is an array and i need only the value of the first element. The desired output would be like below
{
"products": [
{
"id": 2,
"id_default_image": "21",
"price": "35.900000",
"name": "item 1"
},
{
"id": 4,
"id_default_image": "4",
"price": "29.000000",
"name": "item 2"
}
]
}
I'm working on a react-native project. What would be the easiest way to achieve this? Any help would be greatly appreciated. Thanks.
Similar to Ele's answer but if you don't want to change the original object. You can use map to iterate over the product objects and return a new products array:
const data = {"products":[{"id":2,"id_default_image":"21","price":"35.900000","name":[{"id":"1","value":"item 1"},{"id":"2","value":"item 1 alternate name"}]},{"id":4,"id_default_image":"4","price":"29.000000","name":[{"id":"1","value":"item 2"},{"id":"2","value":"item 2 alternate name"}]}]};
const products = data.products.map(obj => ({ ...obj, name: obj.name[0].value }));
console.log(products);
Also used: spread syntax
Well, you can use the function forEach or a simple for-loop and assign the first value to the attribute name.
let obj = { "products": [ { "id": 2, "id_default_image": "21", "price": "35.900000", "name": [ { "id": "1", "value": "item 1" }, { "id": "2", "value": "item 1 alternate name" } ] }, { "id": 4, "id_default_image": "4", "price": "29.000000", "name": [ { "id": "1", "value": "item 2" }, { "id": "2", "value": "item 2 alternate name" } ] } ]}
obj.products.forEach(o => (o.name = o.name[0].value));
console.log(obj);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Try this
const productsArray = products.map((product, index) => {
const obj = {};
obj["id"] = product["id"];
obj["id_default_image"] = product["id_default_image"];
obj["price"] = product["price"],
obj["name"] = product.name[0].value;
return obj;
});
const obj = {};
obj.products = productsArray;
console.log(obj);//will print you the desired output you want

Comparing arrays of objects and remove duplicate [duplicate]

This question already has answers here:
Remove duplicates in an object array Javascript
(10 answers)
Closed 5 years ago.
I have an array containing arrays of objects which I need to compare.
I've looked through multiple similar threads, but I couldn't find a proper one that compares multiple arrays of objects (most are comparing two arrays of objects or just comparing the objects within a single array)
This is the data (below is a JSFiddle with code sample)
const data = [
[
{
"id": "65",
"name": "Some object name",
"value": 90
},
{
"id": "89",
"name": "Second Item",
"value": 20
}
],
[
{
"id": "89",
"name": "Second Item",
"value": 20
},
{
"id": "65",
"name": "Some object name",
"value": 90
}
],
[
{
"id": "14",
"name": "Third one",
"value": 10
}
]
]
I want to remove all duplicate arrays of objects, regardless of the length of data (there could be a lot more records).
I managed to get the unique ones extracted into an object:
const unique = data.reduce(function(result, obj) {
return Object.assign(result, obj)
}, [])
That doesn't work for me though, because I need 1 of the duplicated arrays to remain and the returned data to be an array as well, instead of an object. E.g.:
// result I need
[
[
{
"id":"65",
"name":"Some object name",
"value":90
},
{
"id":"89",
"name":"Second Item",
"value":20
}
],
[
{
"id":"14",
"name":"Third one",
"value":10
}
]
]
So how do I compare each array of objects to the others in the parent array and preserve one of each duplicated or unique array of objects?
JSFiddle
you can achieve so by using function.As below. Not sure about best optimum way of doing so.
var testArray = [
[
{
"id": "65",
"name": "Some object name",
"value": 90
},
{
"id": "89",
"name": "Second Item",
"value": 20
}
],
[
{
"id": "89",
"name": "Second Item",
"value": 20
},
{
"id": "65",
"name": "Some object name",
"value": 90
}
],
[
{
"id": "14",
"name": "Third one",
"value": 10
}
]
]
function removeDuplicatesFromArray(arr){
var obj={};
var uniqueArr=[];
for(var i=0;i<arr.length;i++){
if(!obj.hasOwnProperty(arr[i])){
obj[arr[i]] = arr[i];
uniqueArr.push(arr[i]);
}
}
return uniqueArr;
}
var newArr = removeDuplicatesFromArray(testArray);
console.log(newArr);
const data = [
[
{
"id": "65",
"name": "Some object name",
"value": 90
},
{
"id": "89",
"name": "Second Item",
"value": 20
}
],
[
{
"id": "89",
"name": "Second Item",
"value": 20
},
{
"id": "65",
"name": "Some object name",
"value": 90
}
],
[
{
"id": "14",
"name": "Third one",
"value": 10
}
]
];
const temp = {};
const result = [];
data.forEach(itemArr => {
const items = itemArr.filter(item => {
const isUnique = temp[`${item.id}-${item.name}-${item.value}`] === undefined;
temp[`${item.id}-${item.name}-${item.value}`] = true;
return isUnique;
});
if (items.length !== 0)
result.push(items);
});
console.log(result);

Underscore filter array of object using like query

I have the below Json.
{
"results": [
{
"id": "123",
"name": "Some Name"
},
{
"id": "124",
"name": "My Name"
},
{
"id": "125",
"name": "Johnson Johnson"
},
{
"id": "126",
"name": "Mike and Mike"
},
{
"id": "201",
"name": "abc xyz"
},
{
"id": "202",
"name": "abc befd"
},
{
"id": "210",
"name": "jki yuiu"
},
{
"id": "203",
"name": "asdfui uiuu"
},
{
"id": "204",
"name": "sfdhu uiu"
},
{
"id": "205",
"name": "asdfui uyu"
}
]
}
Using Underscore i want to filter the above data using sql like query on id.
for example if pass "2" the json should be filtered and return a new json which contain id starting with 2, If i pass 20 it should return new json with id starting with 20
similar to sql like query and then return n results matching,
correction: I want the data starting with id 2 or whatever parameter i pass i need data starting with it
Try this
function getResult(keyToFilter, valueStartsWith){
return _.filter(results, function(d){ return d[keyToFilter].startsWith(valueStartsWith); })
}
getResult("name", "asdfui");
[{
"id": "203",
"name": "asdfui uiuu"
},
{
"id": "205",
"name": "asdfui uyu"
}]
What about Array.prototype.filter and Array.prototype.slice? (underscore has similar functions but why to use them when it can be solved with plain JS)
function sqlLikeFilter(data, id, maxn) {
return data.result.filter(function(x) { return x.id == id; }).slice(0, maxn);
}
console.log(sqlLikeFilter(yourData, 125, 1));
Try this
function(id){
var result = _.filter(results, function(value) {
return value.id === id
})
return result;
}

remove duplicate value existing object from multidimensional array object in javascript

This is my javascript array:
[{
"id": "44",
"name": "chathura"
}, {
"id": "45",
"name": "gayan"
}, {
"id": "48",
"name": "sunimal"
}, {
"id": "47",
"name": "chathura"
}, {
"id": "20",
"name": "yasith"
}, {
"id": "21",
"name": "thisaru"
}, {
"id": "42",
"name": "insaf"
}, {
"id": "63",
"name": "sunimal"
}, {
"id": "78",
"name": "yasith"
}, {
"id": "36",
"name": "thisaru"
}]
I want to remove duplicate name existing object element from this array and get the following:
[{
"id": "47",
"name": "chathura"
}, {
"id": "45",
"name": "gayan"
}, {
"id": "48",
"name": "sunimal"
}, {
"id ": "20",
"name ": "yasith "
}, {
"id ": "21 ",
"name ": "thisaru"
}, {
"id ": "42 ",
"name ": "insaf"
}]
How can I remove duplicates?
You can iterate through the array and use a hash table to filter any IDs that have already been used:
function getUniqueNames(nameObjects) {
var existingIds = { };
return nameObjects
.filter(function(nameObject) {
var id = nameObject.id;
var alreadyExists = existingIds[id];
existingIds[id] = true;
return alreadyExists;
});
I'm not sure about your use case, but it might make sense in your case just to convert the data into a Map. Maps work similar to a hash table, and will map each name to its ID. They enforce uniqueness by design:
var names = nameObjects
.reduce(function(map, nameObject) {
map.set(nameObject.id, nameObject.name);
return map;
}, new Map());
// Look up a name by ID
names.get(47);
// Do something for every name
names.forEach(function(name, key) {
console.info(name, 'has ID', key);
});
Maps are ES6 and you may need a polyfill for some browsers.
Try this worked solution, using push method :
JS :
var arr = {};
for ( var i=0; i < x.length; i++ )
arr[x[i]['name']] = x[i];
var result = new Array();
for ( var key in arr )
result.push(arr[key]);
That will return an array of objects result that contain a non duplicated objects.
Result :
[{
"id": "47",
"name": "chathura"
}, {
"id": "45",
"name": "gayan"
}, {
"id": "48",
"name": "sunimal"
}, {
"id ": "20",
"name ": "yasith "
}, {
"id ": "21 ",
"name ": "thisaru"
}, {
"id ": "42 ",
"name ": "insaf"
}]
Hope this will help.

split out object property and values from an array [duplicate]

This question already has answers here:
Remove a JSON attribute [duplicate]
(2 answers)
Closed 7 years ago.
From this json arrays
{
"result": [
{
"id": "1",
"name": "John",
"type": "B",
"score":"passed"
},
{
"id": "2",
"name": "Alice",
"type": "A",
"score":"failed"
}
]
}
How to split out some field and turn it intosomething like this
{
"result": [
{
"id": "1",
"type": "B",
},
{
"id": "2",
"type": "A",
}
]
}
I do not want to use splice in my case, above is just sample code.
Try this:
var input = {
"result": [
{
"id": "1",
"name": "John",
"type": "B",
"score":"passed"
},
{
"id": "2",
"name": "Alice",
"type": "A",
"score":"failed"
}
]
};
var output = {
result: input.result.map(function(item) {
return {
id: item.id,
type: item.type
};
})
}
Try like this
var json = {
"result": [{
"id": "1",
"name": "John",
"type": "B",
"score": "passed"
}, {
"id": "2",
"name": "Alice",
"type": "A",
"score": "failed"
}
]
};
json.result.forEach(function(item) {
delete item.name;
delete item.score;
});
console.log(json);
iterate over arry and remove age property
var json = [
{"name":"john",
"age":"30",
"gender":"male"},
{"name":"Alice",
"age":"20",
"gender":"female"}
];
json.forEach(function(x){
delete x['age'];
})

Categories

Resources