Add item from json array using its name / value [duplicate] - javascript

This question already has answers here:
Alter and Assign Object Without Side Effects
(7 answers)
Closed 6 years ago.
I know how to remove an item from a json array, but I can't seem to make it work when adding.
The array:
var users = [
{name: 'james', id: '1'}
]
Want to add so it becomes:
var users = [
{name: 'james', id: '1'},
{name: 'thomas', id: '2'}
]
Here's the code for removing an array:
Array.prototype.removeValue = function(name, value){
var array = $.map(this, function(v,i){
return v[name] === value ? null : v;
});
this.length = 0; //clear original array
this.push.apply(this, array); //push all elements except the one we want to delete
}
removeValue('name', value);
//space removed
What changes would I need to make to reverse to add values to the array?

With Array.prototype.push() ?
var sports = ["plongée", "baseball"];
var total = sports.push("football", "tennis");
console.log(sports); // ["plongée", "baseball", "football", "tennis"]
console.log(total); // 4

I think a more fitting function is filter than map.
Array.prototype.removeValue = function(name, value){
var array = $.filter(this, function(v,i){
return v[name] !== value;
});
this.length = 0; //clear original array
this.push.apply(this, array); //push all elements except the one we want to delete
}
I am only assuming the length and push hacks work, since I've never used them myself.

Related

Removing the duplicate object in Array in javascript by comparing with key of the object? [duplicate]

This question already has answers here:
How to remove all duplicates from an array of objects?
(77 answers)
Closed 4 years ago.
I have an Array I want to remove duplicate object example bison is coming 2 times.
var beasts = [ {'ant':false}, {'bison':true}, {'camel':true}, {'duck':false}, {'bison':false} ];
This is what I tried
let a = beasts.indexOf(bison);
console.log(a);
But all the time it give -1 that means the object is not there at all
please ignore the values of the object
Use Array.filter and Set
Maintain a set of unique keys and if the value exists in the set, return false else add it to set and return true.
var beasts = [ {'ant':false}, {'bison':true}, {'camel':true}, {'duck':false}, {'bison':false} ];
let set = new Set();
let result = beasts.filter(o => {
// Get the key of object
let key = Object.keys(o)[0];
if(!set.has(key)) { // check for existence in set
// if does not exist add it to set and return true (filter IN)
set.add(key);
return true;
}
});
console.log(result);
In a simple way
const beasts = ['John', 'Paul', 'George', 'Ringo', 'John'];
let beasts = [...new Set(names)];
console.log(unique); // 'John', 'Paul', 'George', 'Ringo'
To do this programmatically, maintain a separate array that will hold names of processed beasts and then reduce the original array in relation to processedBeastsArray;
var beasts = [ {'ant':false}, {'bison':true}, {'camel':true}, {'duck':false}, {'bison':false} ];
const processedBeasts = [];
const result = beasts.reduce(function(final, current) {
const currentBeastName = Object.keys(current)[0];
if(!processedBeasts.includes(currentBeastName)){
processedBeasts.push(currentBeastName);
final.push(current);
}
return final;
}, []);
You can also use a simple forEach() loop that has O(n) complexity to get that output.
var beasts = [ {'ant':false}, {'bison':true}, {'camel':true}, {'duck':false}, {'bison':false} ];
var resObj = {};
beasts.forEach((beast)=>{
var key = Object.keys(beast)[0];
if(!resObj[key]){
resObj[key] = beast;
}
});
var finalArrayRes = Object.values(resObj);
console.log(finalArrayRes);

Javascript: Combining Strings into Array [duplicate]

This question already has answers here:
Javascript: How to Combine & Filter Arrays
(4 answers)
Closed 5 years ago.
I have 3 strings that I need to convert into a single array, from there I want to filter out the type: "bundle".
I need to note that I'm using Javascript Code by Zapier and their javascript library is a bit limited as far as the functions that I can use, but this is what I have so far which works if I hard code itemArray. I'm just having trouble creating my itemArray from the 3 given strings:
Strings:
var type = 'bundle, simple, simple';
var name = 'Product1, Product2, Product3';
var price = '1.99, 2.99, 3.99';
I need to figure out how to convert the above 3 strings above into the following array using javascript:
var itemArray = [
{type:"bundle", info: {name: "Product1", price: "1.99"}},
{type:"simple", info: {name: "Product2", price: "2.99"}},
{type:"simple", info: {name: "Product3", price: "3.99"}}];
From there I'm looking to filter out the bundle product type and only return the simple product types, I'm doing that with the following code:
// Using a for loop
var filtered = [];
for (var i = 0; i < itemArray.length; ++i) {
var item = itemArray[i];
if (item.type == 'simple') filtered.push(item);
}
return {filtered}; //this returns just the 2 simple product type arrays
So my question is, how do I take those 3 strings that I began with and convert those into my itemArray format using javascript?
First make the strings into arrays of the three strings you want. Then in a for loop you can push all of them in whatever (identical) format you want, since all 3 lists have 3 elements each. then you can use the filter function to easily filter out the bundle elements as below.
The following snippet will print out the item array and the filtered value you requested
var types = 'bundle, simple, simple'.split(", ");
var names = 'Product1, Product2, Product3'.split(", ");
var prices = '1.99, 2.99, 3.99'.split(", ");
var itemArray = [];
for(var i = 0; i < 3; i++){
itemArray.push({"type": types[i], "info":{"name": names[i], "price": prices[i]}});
}
console.log(itemArray);
var filtered = [];
for (var i = 0; i < itemArray.length; ++i) {
var item = itemArray[i];
if (item["type"] === 'simple') filtered.push(item);
}
console.log({filtered});
var type = 'bundle, simple, simple'.split(', '), // split the
nameArr = 'Product1, Product2, Product3'.split(', '), // strings to
priceArr = '1.99, 2.99, 3.99'.split(', '), // get the arrays
res = type.map((v,i) => Object.assign({}, {type: v, info: {name: nameArr[i], price: priceArr[i]}})), //map the objects with specified keys and values from given arrays
result = res.filter(v => v.type != 'bundle'); //remove the `bundle` type elements
console.log(result);

which function to use in order to remove an object from an array

I have an array of objects that I'm trying to loop through to match for a specific value, if found delete that object else return false. Below is the code:
array: [{
obj1:{
id: null,
name:'test',
address: '6857346jfhbdjshb'
},
obj12:{
id: 678346,
name:'test',
address: '63784hgj'
},
obj13:{
id: null,
name:'test',
address: 'tevhgvd'
},
obj15:{
id: 65847,
name:'test',
address: 'djhvwe677ghdgv'
},
obj18:{
address: ""
}
}]
js:
for (var obj in array){
if (array[obj].address === "63784hgj" || array[obj].address === "djhvwe677ghdgv" ||array[prop].address === "")
{
array[obj].destroy(); //equivalent to array[1].destroy() (destroy, delete,remove,hide, pop none of them work)
}
}
I'm not sure which function is the correct one to remove object from array.
You apparently want to filter out certain properties from the single element of your array, which is an object, containing subobjects, when the address property of the subobject matches one or more string values.
Extract the first element of the array, then loop over its properties with a for...in loop. If the subproperty matches, delete the property with delete.
function filterproc(array) {
var o = array[0];
for (var k in o)
if (o[k].address === "....")
delete o[k];
}
To match against multiple possibilities, consider using indexOf, which checks if an array contains some value:
if (['63784hgj', ...].indexOf(o[k]) !== -1) ...
If what you want is what toranaburo described in his answer then nothing to do with mine. :( (inform me to delete mine)
If you want a function which returns the new value do this:
var forbiddenAddressList = ['', '63784hgj', 'djhvwe677ghdgv'];
var newArray = myArray.filter(i => forbiddenAddressList.indexof(i.address) === -1);
another way:
var newArray = [];
for (var i = 0; i < myArray.length; i++)
if(forbiddenAddressList.indexof(i.address) === -1)
newArray.push(myArray[i]);
So if what you're asking is to loop through an array of objects, and if the value of a property is found then delete the object it belongs to, then this is what I came up with.
var array = [
{id: null,name:'test',address: '6857346jfhbdjshb'},
{id: 678346,name:'test',address: '63784hgj'},
{id: null,name:'test',address: 'tevhgvd'},
{id: 65847,name:'test',address: 'djhvwe677ghdgv'},
{address: ""}
];
for (var obj in array){
if (array[obj].address === "63784hgj" || array[obj].address === "djhvwe677ghdgv" || array[obj].address === "")
{
array.splice(obj, 1);
}
}
I modified your array of objects, but everything except Obj1, Obj2 etc. remains because arrays are already indexed, thus array[0] refers to Obj1. Also in your if statement you had array[prop] which is undefined, so be sure to change it in your code. This worked for what I think you were trying to do, so let me know if it helps.

Remove a record in a Object Array jQuery

EDIT : Included more details
Hi I have a Object Array in jQuery which looks like this,
My question is how can I delete a record from that object array by columnheader as parameter. I know there is this
var result = $.grep(records, function(e){ return e.columnheader == currentheader; });
but grep i only used to check if there's a matching data based on currentheader that i passed in. What if I want to delete?
I want to delete a record on the fly as I am looping in that object array, lets I have. data contains all object arrays that is shown in the image.
$.each(data, function(key,value) {
// Let's say I want the code here to delete a record in the current object array that I'm looping into.
});
Thanks
You can use filter()
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
arr = arr.filter(function(e) {
return e.columnheader !== currentheader;
});
Demo
var arr = [{
name: 'John Skeet',
rank: 1
}, {
name: 'T.J.Crowder',
rank: 10
}];
console.log(arr);
arr = arr.filter(function(e) {
return e.rank !== 10
});
console.log(arr);
UPDATE
I want the code here to delete a record in the current object array that I'm looping into
Changing a property from object in array.
var arr = [{
name: 'John Skeet',
rank: 1
}, {
name: 'T.J.Crowder',
rank: 10
}];
$.each(arr, function(index, obj) {
if (obj.rank === 10) {
arr[index].rank = 9;
}
});
console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
You can use the JavaScript splice method to do it. First find the index of your object in the array then use the method like that :
your_array.splice(obj_index,0);
EDIT
The easy way but not optimized is to use a for loop to get the index, a better solution is to use linq.js to get the object, then your_array.indexOf(your_obj);
EDIT 2
You can download linq.js here Linq.js
You can use it like this:
function DelteObjFromArray(your_value){
var objToDelete = Enumerable.From(your_array).Where(function (x) { return x.your_property == your_value; }).FirstOrDefault();
var objIndex = your_array.indexOf(objToDelete);
your_array.splice(objIndex,1);
}

Javascript: How to find key name in array of objects [duplicate]

This question already has answers here:
How to check if object property exists with a variable holding the property name?
(11 answers)
Closed 7 years ago.
I am trying to determine if a key name is present in my array of object. As an example, how would I verify if the key with a name of 'name' equals the argument passed in my function call? Below is code to further clarify.
var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
var test = function(arr, propName){
var result = [];
for(var i = 0; i < arr.length; i++){
if(arr[i][propName] === propName){
result.push(arr[i][propName]);
}
}
return result;
}
func(stooges, "name");
Using underscore.js:
var names = _.pluck(stooges, 'name');
In fact this is the very example given on their page?!
So, on the basis that you knew this, but want to know how to write something similar:
function pluck(array, prop]) {
return array.map(function(entry) {
return entry[prop];
});
}
or more safely, returning an empty array if the initial array is undefined:
function pluck(array, prop]) {
return array ? array.map(function(entry) {
return entry[prop];
}) : [];
}

Categories

Resources