How to remove object by property in javascript - javascript

I would like to know how to remove the object by property in nested array object
I have whole list of object in sampleobj, compare each id with apitrans, apifund, if success is false, remove obj in sampleobj
Remove the object if the success is false, in sampleobj.
I have tried:
var result = sampleobj.foreach(e=>{
if(e.id === "trans" && apitrans.success== true){
Object.assign(e, apitrans);
}
if(e.id === "fund" && apifund.success== true){
Object.assign(e, apifund);
}
// if success false remove the object.
})
//inputs scenario 1
var sampleobj=[{
id: "trans",
amount: "100",
fee: 2
},
{
id: "fund",
amount: "200",
fee: 2
}]
var apitrans =
{
success: true,
id: "trans",
tamount: "2000",
fee: "12"
}
var apifund =
{
success: false,
id: "fund",
tamount: "4000",
fee: "10"
}
//inputs scenario 2 how to do same if property name differs
if error, status error, or success false remove obj in sampleobj
var sampleobj=[{
id: "trans",
amount: "100",
fee: 2
},
{
id: "fund",
amount: "200",
fee: 2
},
{ id: "insta", amount: "400", fee: 2 }
]
var apitrans = {success: true,id: "trans",tamount: "2000",fee: "12"}
var apiinsta = { errors: [{code:"error.route.not.supported"}],id: "insta",tamount: "2000",fee: "12"}
var apifund = { status: "error", id: "fund", tamount: "4000", fee: "10" }
var sampleobj=[{
//Expected Output
result: [
{
id: "trans",
amount: "100",
fee: 2
}
]```

You can use filter() to remove elements from array.
Create a helper function(func) which takes two objects as parameter and compare id property of both and check success property of one of them.
Then use filter() of the given array and put both given objects array [apitrans,apifund].
Then use some() method on [apitrans,apifund] and check if any of them have id equal the current element using Helper Function.
var arr=[ { id: "trans", amount: "100", fee: 2 }, { id: "fund", amount: "200", fee: 2 } ]
var apitrans = {success: true,id: "trans",tamount: "2000",fee: "12"}
var apifund = { success: false, id: "fund", tamount: "4000", fee: "10" }
const func = (obj1,obj2) => obj1.id === obj2.id && obj2.success
const res = arr.filter(x => [apitrans,apifund].some(a => func(x,a)));
console.log(res)

You can filter out your array with conditions i.e filter gives you new array instead of changing the original array
var arr = [{
id: "trans",
amount: "100",
fee: 2
},
{
id: "fund",
amount: "200",
fee: 2
}
]
var apitrans = {
success: true,
id: "trans",
tamount: "2000",
fee: "12"
}
var apifund = {
success: false,
id: "fund",
tamount: "4000",
fee: "10"
}
var filter = arr.filter(function(item) {
//console.log(item);
if (item.id === apitrans.id && apitrans.success) {
return item
}
});
console.log(filter);
Or if you want an original array to be modified instead of getting a new array, you can use your given approach with some update i.e
var arr = [{
id: "trans",
amount: "100",
fee: 2
},
{
id: "fund",
amount: "200",
fee: 2
}
]
var apitrans = {
success: true,
id: "trans",
tamount: "2000",
fee: "12"
}
var apifund = {
success: false,
id: "fund",
tamount: "4000",
fee: "10"
}
arr.forEach(e => {
if (e.id === "trans" && apitrans.success == true) {
Object.assign(e, apitrans);
} else if (e.id === "fund" && apifund.success == true) {
Object.assign(e, apifund);
} else {
// if success false remove the object.
var index = arr.indexOf(e);
arr.splice(index, 1);
}
})
console.log("resulted original arr", arr)

Related

Sort by multiple objects in a array in Javascript

var customersObj= [
{ recordId: "123", groupID: "1992" ,memberID:"10" Name : "John" },
{ recordId: "141", groupID: "1994" ,memberID:"13", Name : "Arrow" },
{ recordId: "111", groupID: "1991",memberID:"12", Name : "Mike" }
];
I need to return the array by sort them first by recordId, then by groupID, then by memberID ...
I tried this but didn't get expected result"
return _.sortBy(customersObj,'recordID','groupID','memberID');
Can someone assist here on this...
Pay attention that your *ID are strings, so, I've used Array.map to convert them to ints, and then _.sortBy works expectedly.
I've added additional values to check the sub-sorting.
const customersObj = [{
recordId: "123",
groupID: "1992",
memberID: "10",
Name: "John"
}, {
recordId: "141",
groupID: "1994",
memberID: "13",
Name: "Arrow"
}, {
recordId: "111",
groupID: "1991",
memberID: "12",
Name: "Mike"
}, {
recordId: "123",
groupID: "1991",
memberID: "12",
Name: "Sean"
}, {
recordId: "123",
groupID: "1991",
memberID: "11",
Name: "Sara"
}];
const result = customersObj.map(item => ({
recordId: parseInt(item.recordId, 10),
groupID: parseInt(item.groupID, 10),
memberID: parseInt(item.memberID, 10),
Name: item.Name
}));
console.log(_.sortBy(result, 'recordId', 'groupID', 'memberID'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
Try use this approach:
const customersObj= [
{ recordId: "123", groupID: "1992" ,memberID:"10", Name : "John" },
{ recordId: "141", groupID: "1994" ,memberID:"13", Name : "Arrow" },
{ recordId: "111", groupID: "1991",memberID:"12", Name : "Mike" }
];
const sorted = customersObj.sort((a,b)=>{
return a.recordId - b.recordId || a.groupID - b.groupID || a.memberID - b.memberID;
})
console.log(`sorted`, sorted);
you can use sort method with lambda function to sort.
const list = [
{ color: 'white', size: 'XXL' },
{ color: 'red', size: 'XL' },
{ color: 'black', size: 'M' }
]
list.sort((a, b) => (a.color > b.color) ? 1 : -1) // you can add different conditions here.
to sort multiple fields, do it like this
customersObj.sort(function(a, b) {
return a["recordId"] - b["recordId"] || a["groupID"] - b["groupID"] || a["memberID"] - b["memberID"];
});
You can sort array of object using multiple values by the following method
var arrayOfObj = [
{ recordId: "123", groupID: "1992" ,memberID:"10" , Name : "John" },
{ recordId: "141", groupID: "1994" ,memberID:"13", Name : "Arrow" },
{ recordId: "111", groupID: "1991",memberID:"12", Name : "Mike" }
];
let sortBy = [{
prop:'recordId',
direction: 1
},{
prop:'lastName',
direction: 1
},{
prop:'memberID',
direction: 1
}];
arrayOfObj.sort(function(a,b){
let i = 0, result = 0;
while(i < sortBy.length && result === 0) {
result = sortBy[i].direction*(a[ sortBy[i].prop ].toString() < b[ sortBy[i].prop ].toString() ? -1 : (a[ sortBy[i].prop ].toString() > b[ sortBy[i].prop ].toString() ? 1 : 0));
i++;
}
return result;
})
console.log(arrayOfObj, ":::::");
With lodash, could take an array of keys and take the right spelling of the wanted keys.
var customersObj = [{ recordId: "123", groupID: "1992", memberID: "10", Name: "John" }, { recordId: "141", groupID: "1994", memberID: "13", Name: "Arrow" }, { recordId: "111", groupID: "1991",
memberID: "12", Name: "Mike" }];
console.log(_.sortBy(customersObj, ['recordId', 'groupID', 'memberID']));
// ^ ^ ^
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
Hi i tried solve your problem :)
const display = document.querySelector(".display");
var customersObj= [
{ recordId: "123", groupID: "1992" ,memberID:"10", Name : "John" },
{ recordId: "141", groupID: "1994" ,memberID:"13", Name : "Arrow" },
{ recordId: "111", groupID: "1991",memberID:"12", Name : "Mike" }
];
customersObj.sort(function (a, b) {
return a.recordId - b.recordId || b.groupID - a.groupID || c.memberID - c.memberID;
});
customersObj.map(obj => {
const item = document.createElement("div");
item.textContent += obj.recordId + " " + obj.groupID + " " + obj.memberID +" "+ obj.Name;
display.appendChild(item);
});
<div class="display">
</div>

How to assign values by property in nested object array using javascript

I would like to know how to assign values to object property in nested object by id=insta in javascript
I have a two objects, I need apply one object property to another using javascript
I got stuck and dont know how to proceed,
obj1.forEach(e=> {if(e.id==='insta') Object.assign(e, obj2)})
var obj1 = [
{
id: "insta",
rate: "2.4",
fee: "0",
amount: "400"
},
{
id: "trans",
rate: "1.4",
fee: "0",
amount: "200"
}
]
var obj2 =
{
data: {
rate_value: "4.4",
fee_value: "10",
targetamount: "5000",
country_code: "SG"
}
}
Expected Output:
res= [
{
id: "insta",
rate: "4.4",
fee: "10",
amount: "5000",
country_code: "SG"
}
]
As your expected output shows you only want the items whose id="insta" so use filter() to get those. Then use map() and create a temporary object inside map. And return the combined object using Spread Operator.
Note: You need to create another object because properties name in obj2 and array are different.
var obj1 = [ { id: "insta", rate: "2.4", fee: "0", amount: "400" }, { id: "trans", rate: "1.4", fee: "0", amount: "200" }]
var obj2 = { data: { rate_value: "4.4", fee_value: "10", targetamount: "5000", country_code: "SG" } }
const res = obj1.filter(x => x.id === "insta").map(x => {
const {data} = obj2
let temp = {
rate : data.rate_value,
fee : data.fee_value,
amount : data.targetamount,
country_code : data.country_code
}
return {...x,...temp}
})
console.log(res)
We can use the reduce method to reduce the array to the result we intend to. Here I add the the if condition and mapping values from obj2 in the callback of the reduce method. Basically the filtering and mapping is done, inside the reduce callback method.
var obj1 = [{
id: "insta",
rate: "2.4",
fee: "0",
amount: "400"
},
{
id: "trans",
rate: "1.4",
fee: "0",
amount: "200"
}
]
var obj2 = {
data: {
rate_value: "4.4",
fee_value: "10",
targetamount: "5000",
country_code: "SG"
}
}
const result = obj1.reduce((acc, curr) => {
if (curr.id === 'insta') {
acc.push({
...curr,
rate: obj2.data.rate_value,
fee: obj2.data.fee_value,
amount: obj2.data.targetamount,
country_code: obj2.data.country_code
})
}
return acc;
}, []);
console.log(result);
First of all, you can Array.filter the array to contain object with id = "insta" then apply the data from obj2 to each one of the items using Array.map.
Something like that:
var obj1 = [{
id: 'insta',
rate: '2.4',
fee: '0',
amount: '400',
},
{
id: 'trans',
rate: '1.4',
fee: '0',
amount: '200',
},
];
var obj2 = {
data: {
rate_value: '4.4',
fee_value: '10',
targetamount: '5000',
country_code: 'SG',
},
};
const result = obj1
.filter(item => item.id === 'insta')
.map(item => ({
id: item.id,
rate: obj2.data.rate_value,
fee: obj2.data.fee_value,
amount: obj2.data.targetamount,
country_code: obj2.data.country_code,
}));
console.log(result)

how to overwrite the existing object using javascript

I would like to know how to add existing matched values in object and add the remaining values in javascript
for example, i need to merge_obj with my_obj having id '1' , matched values targetAmount only replace and remaining properties need to add
I tried
var filtervalue = my_obj.filter((e)=>e.id == "1").map((e)=>Object.assign({},e[0], merge_obj));
const merge_obj = {
targetAmount: 50688.97,
type: "REGULAR"
}
const my_obj = [
{
id: "1",
logo: "img1.png",
name: "fund",
speed: "1 Days",
targetAmount: "2000"
},
{
id: "2",
logo: "img2.png",
name: "transfer",
speed: "1 Days",
targetAmount: "3000"
},
]
Expected Output:
var my_obj = [
{
id: "1",
logo: "img1.png",
name: "fund",
speed: "1 Days",
targetAmount: 50688.97,
type: "REGULAR",
},
{
id: "2",
logo: "img2.png",
name: "transfer",
speed: "1 Days",
targetAmount: "3000",
},
]
This can be achieved my using the array map method to iterate through the array of objects, checking if the id is equivalent to '1', followed by using ES6's spread syntax to 'merge' the objects.
const result = my_obj.map(obj => {
if (obj['id'] === '1') {
return {...obj, ...merge_obj}
} else {
return obj;
}
})
console.log(result)
Also, just a quick advice, try to use const and let instead of var!
Just merge the first one by checking id:
var my_obj = [{
id: "1",
logo: "img1.png",
name: "fund",
speed: "1 Days",
targetAmount: "2000"
},
{
id: "2",
logo: "img2.png",
name: "transfer",
speed: "1 Days",
targetAmount: "3000"
},
]
var merge_obj = {
targetAmount: 50688.97,
type: "REGULAR"
};
var new_obj = my_obj.map(e => {
if (e.id == "1") {
Object.keys(merge_obj).forEach(key => e[key] = merge_obj[key]);
}
return e;
});
console.log(new_obj);
.as-console-wrapper { max-height: 100% !important; top: auto; }
If you want to mutate the original just loop over your array and assign directly
var my_obj = [{
id: "1",
logo: "img1.png",
name: "fund",
speed: "1 Days",
targetAmount: "2000"
},
{
id: "2",
logo: "img2.png",
name: "transfer",
speed: "1 Days",
targetAmount: "3000"
},
]
var merge_obj = {
targetAmount: 50688.97,
type: "REGULAR"
};
my_obj.forEach(e=> {if(e.id==='1') Object.assign(e, merge_obj)})
console.log(my_obj)
Change the object accessor in the map function from e[0] to e only, and check if that works.
i.e.
var filtervalue = myList.filter((e)=>e.id == "1").map((e)=>Object.assign({}, e, merge_obj));
Also, you need to check your variable names properly whether its my_obj or myList.

how to overwrite the nested array object in javascript

I would like to know how to merger and overwrite the already existed object value in nested array in javascript.
As shown below, i need to merge the other_obj to obj with id = "zen" and overwrite if the property exists else merge
var obj =[
{id:"abc",
amount: "100",
fee: "5.5"},
{id:"xyz",
amount: "1000",
fee: "5.5"},
{id:"zen",
amount: "500",
fee: "5.5"}]
var other_obj = {
amount: 600,
name: "new"
}
Expected Output:
{
id:"zen",
amount: 600,
fee: "5.5",
name: new
}
Use ... spread syntax:
var obj = [{
id: "abc",
amount: "100",
fee: "5.5"
},
{
id: "xyz",
amount: "1000",
fee: "5.5"
},
{
id: "zen",
amount: "500",
fee: "5.5"
}
];
var other_obj = {
amount: 600,
name: "new"
};
var test = {};
obj.forEach(e => test = {...test, ...e});
test = {...test, ...other_obj};
console.log(test);

Filter things with changeable arguments

let products = [
{
"name": "Lenovo",
"price": "18000",
"model": "v580c"
},
{
"name": "Apple",
"price": "30000",
"model": "Iphone 6"
},
{
"name": "Nikon",
"price": "25000",
"model": "G290"
}]
I need to filter my products array with getProduct function, which accepts changeable list of arguments.
Argument can be either the name of the product and/or price within the minPrice, maxPrice, and/or model.
function getProduct(productName, minPrice, maxPrice, productModel) {
return products.filter(product => {
return product.price < maxPrice && product.price > minPrice && product.name == productName;
});
}
console.log(getProduct("Apple", 3540, 3000000000));
console.log(getProduct("Lenovo", 3540, 3000000000, "v580c"));
You can send an array of params as argument and write a logic to process them accordingly.
Sample:
function getProduct(array, params){
var list = array.filter(function(o){
return params.every(function(kv){
if(o.hasOwnProperty(kv.key)){
var cur = o[kv.key];
switch (kv.operation){
case ">": return cur > kv.value
case "<": return cur < kv.value
case "in": return cur.indexOf(kv.value) > -1
case "regex": return kv.value.test(cur)
default: return cur === kv.value
}
}
})
});
console.log(list);
return list;
}
var products=[{name:"Lenovo",price:"18000",model:"v580c"},{name:"Apple",price:"30000",model:"Iphone 6"},{name:"Nikon",price:"25000",model:"G290"}];
getProduct(products, [{key:"name", value: "Nikon"}])
getProduct(products, [
{key:"price", value: 20000, operation: ">"},
{key:"price", value: 40000, operation: "<"}
])
getProduct(products, [{key:"name", value: "e", operation: "in"}])
getProduct(products, [{key:"model", value: /\d{2,}/g, operation: "regex"}])
You can use an object with special structure for searching, if you need t search for more than one item. This proposal uses an object, with this structure for filtering:
{
name: 'Apple',
price: {
min: 3540, // both or a single border is possible
max: 60000
},
model: function (s) { return s.match(/s/); } // just search for a single letter
}
The algorithm looks for every property in search and if all comparisons are true, then the element is added to the result set.
function filter(array, search) {
return array.filter(function (a) {
return Object.keys(search).every(function (k) {
return (
a[k] === search[k] ||
typeof search[k] === 'object' && (
('min' in search[k]) && ('max' in search[k]) && search[k].min <= a[k] && a[k] <= search[k].max ||
('min' in search[k]) !== ('max' in search[k]) && (search[k].min <= a[k] || a[k] <= search[k].max)
) ||
typeof search[k] === 'function' && search[k](a[k])
);
});
});
}
var products = [{ name: "Lenovo", price: "18000", model: "v580c" }, { name: "Apple", price: "30000", model: "Iphone 6" }, { name: "Nikon", price: "25000", model: "G290" }, { name: "Foo", price: "10", model: "a1" }, { name: "Foo", price: "20", model: "a2" }, { name: "Foo", price: "30", model: "a3" }, { name: "Foo", price: "40", model: "a4" }, { name: "Foo", price: "50", model: "a5" }, { name: "Foo", price: "60", model: "a6" }, { name: "Foo", price: "70", model: "a7" }, { name: "Foo", price: "80", model: "a8" }, { name: "Foo", price: "90", model: "a9" }];
console.log(filter(products, { name: 'Foo', price: { min: 60 } }));
console.log(filter(products, { name: 'Foo', price: { max: 40 } }));
console.log(filter(products, { name: 'Foo', price: { min: 40, max: 60 } }));
console.log(filter(products, { name: 'Apple', price: { min: 3540, max: 60000 } }));
console.log(filter(products, { name: 'Lenovo', price: { min: 3540, max: 60000 }, model: 'v580c' }));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Categories

Resources