Using a function to delete object properties by key name - javascript

I am trying to figure out how I would be able to create a function that would delete an object property based on its key name
const objects = [
{ name: 'Luke' },
{ foo: 'bar' },
{ name: 'Yoda' },
{ name: 'Leia' }
]
Rather than just delete.foo is there a function I could create that would delete any property that didn't have the key 'name'?

You can use Array.prototype.filter and object's hasOwnProperty to solve this problem.
const objects = [
{ name: 'Luke' },
{ foo: 'bar' },
{ name: 'Yoda' },
{ name: 'Leia' }
];
const res = objects.filter(item => item.hasOwnProperty('name'));
console.log(res);
.as-console-wrapper{min-height: 100%!important; top: 0;}

you can filter it;
objects.filter(object => object.name != 'Leia')

You could filter the array and map only objects with name property.
const
objects = [{ name: 'Luke' }, { foo: 'bar' }, { name: 'Yoda' }, { name: 'Leia' }],
result = objects
.filter(o => 'name' in o)
.map(({ name }) => ({ name }));
console.log(result);

Object has hasOwnProperty method, that you can use to filter the elements of your array
Solution
objects.filter(obj => obj.hasOwnProperty('name'))

Related

Using ES6 Syntax to Map an Array of Values to Array of Truncated Objects

I am trying to use .map() and ES6 syntax to return a truncated version of each object in my array. I can do this to get one value from the original object passed on:
return dbJobs.map(job =>
job.data.modType
);
But how would I use ES6 syntax to handle taking an array of objects where each object looks like this:
{
id: 123,
name: "name value",
data: {
modType: "report",
category: "value"
}
}
... and return an array of objects where each object has two properties from the original objects, like this:
{
name: "name value",
modType: "report"
}
You could use a destructuring and map objects with short hand properties.
var dbJobs = [{ id: 123, name: "name value", data: { modType: "report", category: "value" } }],
result = dbJobs.map(({ name, data: { modType } }) => ({ name, modType }));
console.log(result);
So with Array.prototype.map() you can create a new structure based on its function's return value.
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
Think about the following:
const array = [{
id: 123,
name: "name value",
data: {
modType: "report",
category: "value"
}
}];
const result = array.map(e => {
return {
name: e.name,
modeType: e.data.modType
}
});
console.log(result);
Or the same with destructuring:
const array = [{
id: 123,
name: "name value",
data: {
modType: "report",
category: "value"
}
}];
const result = array.map(({name, data: {modType}}) => {
return {
name,
modType
}
});
console.log(result);
I hope that helps!
I believe this will do what you need:
let obj = [{
id: 123,
name: "name value",
data: {
modType: "report",
category: "value"
}
}];
let res = obj.map(item => {
return {
modType: item.data.modType,
category: item.data.category
}
});
console.log(res);
You can try this simple js code
arr = arr.map(item => {
const ob = {} // create temporary object
ob.name = item.name; // asign props from array object
ob.modType = item.data.modType; // asign props from array object
return ob // just return create object
})

Ordering an object with keys and subobjects by a property

I have an object with a sub-object with ids. I would like to order the subobject by a specific property but without loosing the id references.
I've tried ordering individually the subobject "options" by position using lodash and different vanilla js solutions I've found and reasigning it to the main object, but I loose the ids because in all cases it returns an array and I can't find a way to keep the same id structure.
Object example:
{
name: 'User name',
options: {
'234aafg': {
name: 'bar',
position: 2
},
'543al22': {
name: 'foo',
position: 0
},
'437uaz2': {
name: 'baz',
position: 1
},
}
}
Expected Result:
{
name: 'User name',
options: {
'543al22': {
name: 'foo',
position: 0
},
'437uaz2': {
name: 'baz',
position: 1
},
'234aafg': {
name: 'bar',
position: 2
}
}
}
let obj = {
name: 'User name',
options: {
'234aafg': {
name: 'bar',
position: 2
},
'543al22': {
name: 'foo',
position: 0
},
'437uaz2': {
name: 'baz',
position: 1
},
}
}
let keys = Object.keys(obj.options).sort((a, b) => {
if (obj.options[a].position < obj.options[b].position) return -1
return 1
})
let options = obj.options
let newOptions = {}
keys.forEach(key => newOptions[key] = options[key])
obj.options = newOptions
console.log(obj)
I would suggest generating a sorted list of keys that you can later loop over whenever you need. The looping logic would take the key and lookup the original object to get the data it needed for processing, such as displaying the data in order on the page to the user.
var data = {
name: 'User name',
options: {
'234aafg': {
name: 'bar',
position: 2
},
'543al22': {
name: 'foo',
position: 0
},
'437uaz2': {
name: 'baz',
position: 1
},
}
};
data.sortedOptions = Object.entries(data.options)
.sort(function(a, b){
return a[1].position - b[1].position;
})
.map(function(entry){
return entry[0];
});
console.log(data);
This is a simple functional approach that should accomplish what you want. The object entries are converted into an array with an additional id property. After sorting, the id properties are stripped and used to re-construct a new object in the correct order.
However, I would personally skip the call to .reduce and just use the array with the additional id property.
data.options = Object.entries(data.options)
.map(([id, value]) => ({ ...value, id }))
.sort((a, b) => a.position - b.position)
.reduce((rollup, entry) => {
const { id, ...rest } = entry;
rollup[id] = rest;
return rollup;
}, {});

How to access an array of objects which is a key-value pair

i want to access the id 'qwsa221' without using array index but am only able to reach and output all of the array elements not a specific element.
i have tried using filter but couldnt figure out how to use it properly.
let lists = {
def453ed: [
{
id: "qwsa221",
name: "Mind"
},
{
id: "jwkh245",
name: "Space"
}
]
};
Use Object.keys() to get all the keys of the object and check the values in the array elements using . notation
let lists = {
def453ed: [{
id: "qwsa221",
name: "Mind"
},
{
id: "jwkh245",
name: "Space"
}
]
};
Object.keys(lists).forEach(function(e) {
lists[e].forEach(function(x) {
if (x.id == 'qwsa221')
console.log(x)
})
})
You can use Object.Keys method to iterate through all of the keys present.
You can also use filter, if there are multiple existence of id qwsa221
let lists = {
def453ed: [
{
id: "qwsa221",
name: "Mind"
},
{
id: "jwkh245",
name: "Space"
}
]
};
let l = Object.keys(lists)
.map(d => lists[d]
.find(el => el.id === "qwsa221"))
console.log(l)
you can do it like this, using find
let lists = {
def453ed: [
{
id: "qwsa221",
name: "Mind"
},
{
id: "jwkh245",
name: "Space"
}
]
};
console.log(
lists.def453ed // first get the array
.find( // find return the first entry where the callback returns true
el => el.id === "qwsa221"
)
)
here's a corrected version of your filter :
let lists = {def453ed: [{id: "qwsa221",name: "Mind"},{id: "jwkh245",name: "Space"}]};
// what you've done
const badResult = lists.def453ed.filter(id => id === "qwsa221");
/*
here id is the whole object
{
id: "qwsa221",
name: "Mind"
}
*/
console.log(badResult)
// the correct way
const goodResult = lists.def453ed.filter(el => el.id === "qwsa221");
console.log(goodResult)
// filter returns an array so you need to actually get the first entry
console.log(goodResult[0])

Check whether a property of an object exists and only update another property

I have an array with objects that look like this:
let arr = [
{ taxonomy: 'category', id: [ 10, 100 ] },
{ taxonomy: 'post_tag', id: [ 20 ] },
];
I want to be able to push a new object in the array that look like this:
const object = {
taxonomy: 'category',
id: 30
}
What i want is a check if an object in the array with the property value 'taxonomy' already exists, if it does i want to only add the id from the new object in to the existing object. I know how to check if the property already exists but i don't exactly know how to add the new id to the array.
So adding the above object would result in this array:
[
{ taxonomy: 'category', id: [ 10, 100, 30 ] }, // 30 is added
{ taxonomy: 'post_tag', id: [ 20 ] },
];
if it doesn't exist yet it should be added.
Can anybody help me with this?
Use Array.find() to locate an object with the same taxonomy in the array. If one exists, add the id to it. If not, push a clone of the object into the array (after converting the object's id to array):
const addUpdate = obj => {
const current = arr.find(o => obj.taxonomy === o.taxonomy);
if(current) current.id.push(obj.id);
else arr.push({
...obj,
id: [obj.id]
})
};
const arr = [
{ taxonomy: 'category', id: [ 10, 100 ] },
{ taxonomy: 'post_tag', id: [ 20 ] },
];
addUpdate({ taxonomy: 'category', id: 30 });
addUpdate({ taxonomy: 'other', id: 50 });
console.log(arr);
You could find the array and update or push a new object with id as array to the array.
const
array = [{ taxonomy: 'category', id: [ 10, 100 ] }, { taxonomy: 'post_tag', id: [ 20 ] }];
object = { taxonomy: 'category', id: 30 },
item = array.find(({ taxonomy }) => object.taxonomy === taxonomy);
if (item) {
item.id.push(object.id);
} else {
array.push(Object.assign({}, object, { id: [object.id] }));
}
console.log(array);
// remove the last insert
// find item with taxonomy and id
item = array.find(({ taxonomy, id }) => object.taxonomy === taxonomy && id.includes(object.id));
// remove from id by using the index
if (item) item.id.splice(item.id.indexOf(object.id), 1);
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can use the function forEach for looping and pushing the new id.
let arr = [{taxonomy: 'category',id: [10, 100]},{taxonomy: 'post_tag',id: [20]},],
object = {taxonomy: 'category',id: 30};
arr.forEach(({taxonomy, id}) => {
if (object.taxonomy === taxonomy) {
id.push(object.id);
}
});
console.log(arr);
Using an upsert() function like below, you can accomplish this with a little bit of abstraction, so that it can be re-used for more than just this particular schema. upsert() contains some reasonable defaults for the functions, which would work fine if all the objects are dictionaries with primitive values
function upsert (
array, object, keyFn,
updateFn = (target, object) => Object.assign(target, object),
insertFn = object => object
) {
const key = keyFn(object)
const index = array.findIndex(
value => keyFn(value) === key
)
if (index !== -1) updateFn(array[index], object)
else array.push(insertFn(object))
}
let arr = [
{ taxonomy: 'category', id: [10, 100] },
{ taxonomy: 'post_tag', id: [20] }
]
const obj = { taxonomy: 'category', id: 30 }
upsert(
arr, obj,
o => o.taxonomy, // used to determine if existing object should be updated
(t, o) => t.id.push(o.id), // operation for updating existing object
({ id, ...o }) => ({ ...o, id: [id] }) // return new object to insert
)
console.log(arr)

How can I concat an array to an array that is inside an array of objects?

I am trying to concat an array to an array (productsCategories) inside an array of objects.
So, here's what the productCategories array looks like:
[
{
id: 123,
items: [ { Obj1 }, { Obj2 } ]
},
{
id:456,
items: [ { Obj1 }, { Obj2 } ]
}
]
I have some new array, like [ { Obj3 }, { Obj4 } ] that I want to concat to the productCategories for the object where id = 123.
So to do this,
I've first used lodash's find to find the correct object to update and used concat to join the two arrays:
let nextItems:any = find(productCategories, { id: payload.id });
nextItems = assign({}, nextItems, { items: nextItems.items.concat(payload.items)});
So, nextItems.items has the concatenated items array.
However, I am having trouble now adding this to productCategories array. I need to find the object where id is the same as nextItems.id and then set productCategories.items equal to nextItems.items.
What is the correct way to do this?
Find the index of the object that matches the nextItems.id in the productCategories and assign the new concatenated array to it. You can use the lodash findIndex() method to find the index of the object that matches the id.
var index = _findIndex(productCategories, { id: nextItems.id });
productCategories[index].items = nextItems.items;
You can use plain JavaScript just as well. With ES6 spread syntax it can look like this:
productCategories.filter(x => x.id == payload.id)
.forEach(x => x.items.push(...payload.items));
Here is a snippet with sample data:
// Sample data
var productCategories = [{
id: 123,
items: [ { a: 1 }, { a: 2 } ]
}, {
id: 456,
items: [ { b: 1 }, { b: 2 } ]
}];
var payload = {
id: 123,
items: [ { c: 1 }, { c: 2 } ]
};
// Update with payload
productCategories.filter(x => x.id == payload.id)
.forEach(x => x.items.push(...payload.items));
// Show results
console.log(productCategories);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Categories