how to add, update, delete and search object inside array of objects - javascript

Hello I have an empty array, then I push inside objects, but is not getting updated, it going back to empty again. this on node.js. i need to get as the first argument - from the commend line one of three string that do something to the array : 'add' to add new item to the array, 'delete' for delete frm the array and and 'update' for update the array . second argument is name of the book,third argument author, and last arugmnt pages.
let arrayOfBooks = [];
// Assign places to the array
let whichArgument = process.argv[2]
let name = process.argv[3];
let author = process.argv[4];
let pages = Number(process.argv[5]);
// Function constructor
function Book(name,author,pages) {
this.name = name;
this.author = author;
this.pages = pages;
}
// Add function
const addBook = (arrayOfBooks)=> {
arrayOfBooks.push(new Book(name, author, pages));
return arrayOfBooks
}
let result = addBook(arrayOfBooks);

Your method works, but maybe you are loosing the reference by using the same name to the array and the params. But anyway, as the method .push does not return an updated array, just it modifies the same array instance, you don't need to return the pushed array, just use it.
const arrayOfBooks = [
{book: 1},
{book: 2},
{book: 3},
{book: 4},
]
const addBook = (list, book) => {
list.push(book)
}
addBook(arrayOfBooks, {book: 5, isTheNewOne: true})
const result = arrayOfBooks
console.log(result)
// Array with 5 elements now
See in fiddle

Related

How to push all the objects inside an array

It will give data by checking for each variant inside the variant array, it show all the object if the condition matched or undefined if not, but in this particular code, it is creating a new array for each item, something like this :-
[{id: 'something'}] [{id: 'something'}] [{id: 'something'}] [{id: 'something'}]
I want it to have all the result inside one array:-
[
{id: 'something'},
{id: 'something'},
{id: 'something'},
{id: 'something'}
]
const mynewarr = [];
const myimages = product_details.data.product.images;
for(var i = 0; i < product_details.data.product.variants.length; i++) {
const myvari = product_details.data.product.variants[i].image_id;
const real = myimages.find(imageid => imageid.id == myvari);
mynewarr.push(real);
}
Just use a destructuring assignment to "unpack" the array before the push.
mynewarr.push(...real);
If I understand correctly you need to go:
const newArray = product_details.data.product.variants.map((variant) => variant.image_id === 'your_condition' ? { id: variant.image_id } : undefined)
The newArray will contain an array of objects with the ids.
Since your myimages is an array of array, you can push the object by accessing the 0th index of the filtered item(using .find).
If there's a possibility that the .find method might return undefined you can add a conditional check to push only the found items.
You can update your code to something like the below.
const mynewarr = [];
const myimages = product_details.data.product.images;
for(var i = 0; i < product_details.data.product.variants.length; i++){
const myvari = product_details.data.product.variants[i].image_id;
const real = myimages.find(imageid => imageid.id === myvari)
if(real){
mynewarr.push(real[0]); //Add only the object and not the sub array.
}
}

Find Unique value from an array based on the array's string value (Javascript)

so I want to find unique values from an array.
so for example I have this array:
const mainArr = ['shape-10983', 'size-2364', 'size-7800', 'size-4602', 'shape-11073', 'size-15027', 'size-15030', 'size-15033', 'height-3399', 'height-5884']
so I want to find the first matching value for each unique item.
for example, in the array, I have two strings with the shape prefix, six items with the size prefix, and two items with the height prefix.
so I want to output to be something like
const requiredVal = ["shape-10983", "size-2364", "height-3399"]
I want only the first value from any set of different values.
the simplest solution will be to iterate on the list and storing what you got in a dictionary
function removeSimilars(input) {
let values = {};
for (let value of input) {//iterate on the array
let key = value.splitOnLast('-')[0];//get the prefix
if (!(key in values))//if we haven't encounter the prefix yet
values[key] = value;//store that the first encounter with the prefix is with 'value'
}
return Object.values(values);//return all the values of the map 'values'
}
a shorter version will be this:
function removeSimilars(input) {
let values = {};
for (let value of input)
values[value.splitOnLast('-')[0]] ??= value;
return Object.values(values);
}
You could split the string and get the type and use it aks key for an object along with the original string as value. At result take only the values from the object.
const
data = ['shape-10983', 'size-2364', 'size-7800', 'size-4602', 'shape-11073', 'size-15027', 'size-15030', 'size-15033', 'height-3399', 'height-5884'],
result = Object.values(data.reduce((r, s) => {
const [type] = s.split('-', 1);
r[type] ??= s;
return r;
}, {}));
console.log(result);
If, as you mentioned in the comments, you have the list of prefixes already available, then all you have to do is iterate over those, to find each first element that starts with that prefix in your full list of possible values:
const prefixes = ['shape', 'size', 'height'];
const list = ['shape-10983', 'size-2364', 'size-7800', 'size-4602', 'shape-11073', 'size-15027', 'size-15030', 'size-15033', 'height-3399', 'height-5884']
function reduceTheOptions(list = [], prefixes = [], uniques = []) {
prefixes.forEach(prefix =>
uniques.push(
list.find(e => e.startsWith(prefix))
)
);
return uniques;
}
console.log(reduceTheOptions(list, prefixes));
Try this:
function getRandomSet(arr, ...prefix)
{
// the final values are load into the array result variable
result = [];
const randomItem = (array) => array[Math.floor(Math.random() * array.length)];
prefix.forEach((pre) => {
result.push(randomItem(arr.filter((par) => String(par).startsWith(pre))));
});
return result;
}
const mainArr = ['shape-10983', 'size-2364', 'size-7800', 'size-4602', 'shape-11073', 'size-15027', 'size-15030', 'size-15033', 'height-3399', 'height-5884'];
console.log("Random values: ", getRandomSet(mainArr, "shape", "size", "height"));
I modified the #ofek 's answer a bit. cuz for some reason the ??= is not working in react project.
function removeSimilars(input) {
let values = {};
for (let value of input)
if (!values[value.split("-")[0]]) {
values[value.split("-")[0]] = value;
}
return Object.values(values);
}
create a new array and loop over the first array and check the existing of element before in each iteration if not push it to the new array

ES6 Filtering objects by unique attribute

I've an array of errors, each error has a non-unique param attribute.
I'd like to filter the array based on whether the param has been seen before.
Something like this:
const filteredErrors = [];
let params = [];
for(let x = 0; x < errors.length; x++) {
if(!params.includes(errors[x].param)) {
params.push(errors[x].param);
filteredErrors.push(errors[x]);
}
}
But I've no idea how to do this in ES6.
I can get the unique params const filteredParams = Array.from(new Set(errors.map(error => error.param)));
but not the objects themselves.
Pretty sure this is just a weakness in my understanding of higher order functions, but I just can't grasp it
You could destrucure param, check against params and add the value to params and return true for getting the object as filtering result.
As result you get an array of first found errors of the same type.
const
params = [],
filteredErrors = errors.filter(({ param }) =>
!params.includes(param) && params.push(param));
Instead of an array you can make use of an object to keep a map of existing values and make use of filter function
let params = {};
const filteredErrors = errors.filter(error => {
if(params[error.param]) return false;
params[error.param] = true;
return true;
});
i'd probably do it like this with a reduce and no need for outside parameters:
const filteredErrors = Object.values(
errors.reduce((acc, val) => {
if (!acc[val.param]) {
acc[val.param] = val;
}
return acc;
}, {}))
basically convert it into an object keyed by the param with the object as values, only setting the key if it hasn't been set before, then back into an array of the values.
generalized like so
function uniqueBy(array, prop) {
return Object.values(
array.reduce((acc, val) => {
if (!acc[val[prop]]) {
acc[val[prop]] = val;
}
return acc;
}, {}))
}
then just do:
const filteredErrors = uniqueBy(errors, 'param');
If your param has a flag identifier if this param has been seen before then you can simply do this.
const filteredErrors = errors.filter(({ param }) => param.seen === true);
OR
const filteredErrors = errors.filter((error) => error.param.seen);
errors should be an array of objects.
where param is one of the fields of the element of array errors and seen is one of the fields of param object.
You can do it by using Array.prototype.reduce. You need to iterate through the objects in the array and keep the found params in a Set if it is not already there.
The Set.prototype.has will let you find that out. If it is not present in the Set you add it both in the Set instance and the final accumulated array, so that in the next iteration if the param is present in your Set you don't include that object:
const errors = [{param: 1, val: "err1"}, {param: 2, val: "err2"}, {param: 3, val: "err3"}, {param: 2, val: "err4"}, {param: 1, val: "err5"}];
const { filteredParams } = errors.reduce((acc, e) => {
!acc.foundParams.has(e.param) && (acc.foundParams.add(e.param) &&
acc.filteredParams.push(e));
return acc;
}, {foundParams: new Set(), filteredParams: []});
console.log(filteredParams);

Adding elements to object

I need to populate a json file, now I have something like this:
{"element":{"id":10,"quantity":1}}
And I need to add another "element". My first step is putting that json in a Object type using cart = JSON.parse, now I need to add the new element.
I supposed I must use cart.push to add another element, I tried this:
var element = {};
element.push({ id: id, quantity: quantity });
cart.push(element);
But I got error "Object has no method push" when I try to do element.push, and I think I'm doing something VERY wrong because I'm not telling the "element" anywhere.
How can I do that?
Edit: sorry to all I had a LOT of confusion in my head.
I thought I can get only object type when taking data from JSON.parse, but I get what I put in the JSON in the first place.
Putting array instead of object solved my problem, I used lots of suggestions got here too, thank you all!
Your element is not an array, however your cart needs to be an array in order to support many element objects. Code example:
var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push(element);
If you want cart to be an array of objects in the form { element: { id: 10, quantity: 1} } then perform:
var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push({element: element});
JSON.stringify() was mentioned as a concern in the comment:
>> JSON.stringify([{a: 1}, {a: 2}])
"[{"a":1},{"a":2}]"
The line of code below defines element as a plain object.
let element = {}
This type of JavaScript object with {} around it has no push() method. To add new items to an object like this, use this syntax:
element[yourKey] = yourValue
To put it all together, see the example below:
let element = {} // make an empty object
/* --- Add Things To The Object --- */
element['active'] = true // 'active' is the key, and 'true' is the value
console.log(element) // Expected result -> {type: true}
element['state'] = 'slow' // 'state' is the key and 'slow' is the value
console.log(element) // Expected result -> {type: true, state: 'slow'}
On the other hand, if you defined the object as an array (i.e. using [] instead of {}), then you can add new elements using the push() method.
To append to an object use Object.assign
var ElementList ={}
function addElement (ElementList, element) {
let newList = Object.assign(ElementList, element)
return newList
}
console.log(ElementList)
Output:
{"element":{"id":10,"quantity":1},"element":{"id":11,"quantity":2}}
If the cart has to be stored as an object and not array (Although I would recommend storing as an []) you can always change the structure to use the ID as the key:
var element = { quantity: quantity };
cart[id] = element;
This allows you to add multiple items to the cart like so:
cart["1"] = { quantity: 5};
cart["2"] = { quantity: 10};
// Cart is now:
// { "1": { quantity: 5 }, "2": { quantity: 10 } }
Adding new key/pair elements into the original object:
const obj = { a:1, b:2 }
const add = { c:3, d:4, e: ['x','y','z'] }
Object.entries(add).forEach(([key,value]) => { obj[key] = value })
obj new value:
{a: 1, b: 2, c: 3, d: 4, e: ['x', 'y', 'z'] }
I was reading something related to this try if it is useful.
1.Define a push function inside a object.
let obj={push:function push(element){ [].push.call(this,element)}};
Now you can push elements like an array
obj.push(1)
obj.push({a:1})
obj.push([1,2,3])
This will produce this object
obj={
0: 1
1: {a: 1}
2: (3) [1, 2, 3]
length: 3
}
Notice the elements are added with indexes and also see that there is a new length property added to the object.This will be useful to find the length of the object too.This works because of the generic nature of push() function
you should write var element = [];
in javascript {} is an empty object and [] is an empty array.
cart.push({"element":{ id: id, quantity: quantity }});
function addValueInObject(object, key, value) {
var res = {};
var textObject = JSON.stringify(object);
if (textObject === '{}') {
res = JSON.parse('{"' + key + '":"' + value + '"}');
} else {
res = JSON.parse('{' + textObject.substring(1, textObject.length - 1) + ',"' + key + '":"' + value + '"}');
}
return res;
}
this code is worked.
Try this:
var data = [{field:"Data",type:"date"}, {field:"Numero",type:"number"}];
var columns = {};
var index = 0;
$.each(data, function() {
columns[index] = {
field : this.field,
type : this.type
};
index++;
});
console.log(columns);
If anyone comes looking to create a similar JSON, just without using cart as an array, here goes:
I have an array of objects myArr as:
var myArr = [{resourceType:"myRT",
id: 1,
value:"ha"},
{resourceType:"myRT",
id: 2,
value:"he"},
{resourceType:"myRT",
id: 3,
value:"Li"}];
and I will attempt to create a JSON with the following structure:
{
"1":{"resourceType":"myRT","id":"1","value":"ha"},
"2":{"resourceType":"myRT","id":"2","value":"he"},
"3":{"resourceType":"myRT","id":"3","value":"Li"}
}
you can simply do-
var cart = {};
myArr.map(function(myObj){
cart[myObj.id]= myObj;
});
function addValueInObject(value, object, key) {
var addMoreOptions = eval('{"' + key + '":' + value + '}');
if(addMoreOptions != null) {
var textObject = JSON.stringify(object);
textObject = textObject.substring(1,textObject.length-1);
var AddElement = JSON.stringify(addMoreOptions);
object = eval('{' + textObject +','+ AddElement.substring(1,AddElement.length-1) + '}');
}
return object;
}
addValueInObject('sdfasfas', yourObject, 'keyname');
OR:
var obj = {'key':'value'};
obj.key2 = 'value2';
For anyone still looking for a solution, I think that the objects should have been stored in an array like...
var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push(element);
Then when you want to use an element as an object you can do this...
var element = cart.find(function (el) { return el.id === "id_that_we_want";});
Put a variable at "id_that_we_want" and give it the id of the element that we want from our array. An "elemnt" object is returned. Of course we dont have to us id to find the object. We could use any other property to do the find.
My proposition is to use different data structure that proposed already in other answers - it allows you to make push on card.elements and allow to expand card properties:
let card = {
elements: [
{"id":10,"quantity":1}
],
//other card fields like 'owner' or something...
}
card.elements.push({"id":22,"quantity":3})
console.log(card);
push is an method of arrays , so for object you can get the index of last element ,and you can probably do the same job as push for object as below
var lastIndex = Object.keys(element)[Object.keys(element).length-1];
then add object to the new index of element
element[parseInt(lastIndex) +1] = { id: id, quantity: quantity };
if you not design to do loop with in JS e.g. pass to PHP to do loop for you
let decision = {}
decision[code+'#'+row] = event.target.value
this concept may help a bit
This is an old question, anyway today the best practice is by using Object.defineProperty
const object1 = {};
Object.defineProperty(object1, 'property1', {
value: 42,
writable: false
});
object1.property1 = 77;
// throws an error in strict mode
console.log(object1.property1);
// expected output: 42
In case anyone else needs this, I finally found a good way to add objects or arrays of objects:
var myobj = {}
// These two options only work for single-valued keys, not arrays or objects
myobj["a"] = 1
myobj.b = 2
// This one works for everyting:
Object.assign(myobj, {"key": "value"}); // single-value
// Add object
Object.assign(myobj, {"subobj":
{
"c": 3
}
});
// Add array of objects
Object.assign(myobj, {"subarr":
[
{
"d": 4,
},
{
"e": 5
}
]
});
var newObject = {element:{"id":10,"quantity":1}};
console.log(newObject);

method Array.push() javascript

I need to add a new item to array or change the item by id, but When I call the method push, it just creates a new item with a key 0,1,2...
I wrote this array
var finalArray = [];
button.addEventListener('click', function(){
id=123;
writeArray(id, "Jason");
//When I click the button, array always create a new item instead of change the item by id (123).
});
function writeArray(id, name){
var array = {
[id]:{
name: name
}
};
finalArray.push(array);
}
In result, array always creates a new item which is showing below. But I need to change the item by id.
0:{
123: {
name: "Chinga"
}
}
1:{
123: {
name: "Chinga"
}
}
2:{
123: {
name: "Chinga"
}
}
.
.
.
You currently push an object in an array everytime you call your writeArray method, which is not the objective.
As you want to edit an object, using it as a map pretty much, you should access the key (id) you want directly and set the desired value.
finalArray[id] = name;
when I call the method push, it just creates a new item with a key
0,1,2...
push will always add a new item, you need to first check if the item already exists.
function writeArray(id, name){
var index = finalArray.findIndex( function(item, index){
return Object.keys( item )[0] == id;
});
//existing logic
var array = {
[id]:{
name: name
}
};
if ( index == -1 )
{
finalArray.push(array);
}
else
{
finalArray[index] = array;
}
}
What you want is not an array, but an object.
// Initialize object.
var finalObject = {}; /* Changed [] to {} */
function writeToObject(id, name){
finalObject[id] = name;
};
If you still want to use an array, just write finalArray[id] = name but if you got 123 as a number (read: index), that will automatically create empty spaces up to index 123.
I think there are two approaches you can use here:
Instead of an array you can just use an object which simplifies the code pretty much:
finalObject = {};
finalObject[id] = name;
// Structure
finalObject = {'123': 'Jason', '1234': 'John'}
However, if you have to use an actual array, the solution would be to iterate through the array and check if an object with the given ID already exists and if so then modify the name property of it other case just push a new object to the array.
// Structure
finalArray = [{id: '123', 'Jason'}, {id: '1234', 'John'}]
Both could be valid solutions depending on your use case.

Categories