I have an object that looks like this:
let Object1 = { id1: { date: '23-01-2023', status: 'completed' }, id2: { date: '02-01-2023', status: 'pending' } }
How can I make a new object that has only every key of the object, but also the value of one of the keys on the nested object, like this:
let Object2 = { id1: 'completed', id2: 'pending' }
You can map over Object.entries, replacing each value with the status property of that nested object, then create a new object with Object.fromEntries.
let obj1 = { id1: { date: '23-01-2023', status: 'completed' }, id2: { date: '02-01-2023', status: 'pending' } }
let res = Object.fromEntries(Object.entries(obj1).map(([k, v]) => [k, v.status]));
console.log(res);
Get the keys of object1 and use the reduce function to populate the new object.
const object2 = Object.keys(object1).reduce((res, key) => {
res[key] = object1[key].status;
return res;
}, {});
Related
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'))
I have this object in my variable:
{ value1: '237.86', value2: '6.20' }
I would like to get something like this:
[
{name: 'value1', value: '237.86'},
{name: 'value2', value: '6.20'}
]
but I would like to do it in a very agile and nice way.
You can iterate the object using for..in and push the value in an array
let data = {
value1: '237.86',
value2: '6.20'
}
let newData = []
for (let keys in data) {
newData.push({
name: keys,
value: data[keys]
})
}
console.log(newData)
You could get the entries and map key and value as properties.
var data = { value1: '237.86', value2: '6.20' },
result = Object
.entries(data)
.map(([name, value]) => ({ name, value }));
console.log(result);
First get key value pair of the object(in form of array) using Object.entries
Then reduce it, like this:
var object= { value1: '237.86', value2: '6.20' };
var entries= Object.entries(object);
var result = entries.reduce((acc, [key, value])=>{
acc=[{"name": `${key}`, "value" : `${value}`}, ...acc];
return acc;
},[]);
console.log(result)
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
})
I have object:
var roles = { roles: [0: { name: 'admin' }, 1: { name: 'user' }] }
How I can check if value user exists?
I tried do:
console.log(('user' in roles));
But this return false. Why?
With a proper object, you could treat roles.roles as array and find the value with Array#some.
This works for any array like structure with an assignment to an array with Object.assign.
function check(name) {
return Object.assign([], roles.roles).some(o => o.name === name);
}
var roles = { roles: { 0: { name: 'admin' }, 1: { name: 'user' } } };
console.log(check('user'));
console.log(check('bar'));
By taking an array directly, you coult omit the assignment part.
function check(name) {
return roles.roles.some(o => o.name === name);
}
var roles = { roles: [{ name: 'admin' }, { name: 'user' }] };
console.log(check('user'));
console.log(check('bar'));
in operator checks for property not for it's values
let test = {'a':1,'b':2}
console.log('a' in test)
console.log(1 in test)
How can i search values
Here using some method of array i am checking whether desired value is in object or not.
var roles = { roles: [{ name: 'admin' },{ name: 'user' }] }
let searchValue = (input,searchKey) => {
return input.some(( {name} ) => name === searchKey) //
}
console.log(searchValue(roles.roles, 'user'))
console.log(searchValue(roles.roles, 'user not foound'))
I have an array of objects like
[
{id: example1, count: 2}, {id: example2, count:2}
]
which I would like to turn into an object like
{
example1: { id: example1, count: 2},
example2: { id: example2, count: 2},
}
...and so on.
This is supposed to be used in an redux reducer which uses es6 so if something in there is available that is or in lodash.
Answer:
For clarity, this is what I ended up doing as #james-emanon suggested in his answer. It is of course just a matter of using reduce.
case ActionTypes.FETCH_SNAPSHOTS_SUCCESS:
let snapshots = action.payload.reduce((p, c) =>
Object.assign({},
p, {
[c.id]: c
}
), {}
)
return Object.assign({},
state, {
isFetching: false,
lastUpdated: action.meta.receivedAt
},
snapshots
)
how about something like this? (using es6 conventions)
// assuming you action will pass an object like this
var a = [
{id: 'example1', count: 2}, {id: 'example2', count:2}
]
// snippet from reducer
case TYPE.SOME_CASE_CONSTANT:
let newObj = action.yourArrayofObj
.reduce((p,c) => {
return {...p, [c.id]: c}
}, {})
return {
...state,
newObj
}
or
action.yourArrayofObj
.reduce((p,c) => {
p[c.id] = c
return p
}, {})
Something like ?
function arrayToObj(array, keyProperty){
var result = {}
for (var i = 0, l = array.length; i<l;i++)
result[array[i][keyProperty]] = array[i];
return result;
}
Assuming that example1 and example2 are supposed to be strings (e.g., "example1" and "example2"), using es6 arrow-notation:
let arrayToObj = (arr) => {
let o = {};
arr.forEach( (x) => o[x.id]=x );
return o;
};
This is just syntactic sugar over Andrew McCallum's answer.