Set value of a key in an array of objects in ES6? - javascript

Is there a way in ES6, to set value of a key in all objects, in an array of objects to a new value.
[
{title: 'my title', published: false},
{title: 'news', published: true},
...
]
For example, setting every item published value to true?

The array in your example is just a one-dimensional array of objects.
You can do what you asked with forEach and a lambda:
array.forEach(element => element.published = true);

I'd use a loop.
arr represents your array of objects
var result = []
for (var i = 0; i < arr.length; i++) {
result.push([arr[i].title, arr[i].published])
}
console.log(result)
this will result in [['my Title', false], ['news', true]]

Use map
arr = arr.map( s => (s.published = true, s) );
Edit
No need to set the return value either, just
arr.map( s => (s.published = true, s) );
would suffice
Demo
var arr = [{
title: 'my title',
published: false
},
{
title: 'news',
published: true
}
];
arr.map(s => (s.published = true, s));
console.log(arr);

If you don't want a loop you can refer with index.
a = [
{title: 'my title', published: false},
{title: 'news', published: true}
]
a[0].published= true;
a[1].published= true;
or loop it
for (val in a) {
a[val].published = true;
}

You can use the map function with spread operator
let array = [
{ title: 'my title', published: false },
{ title: 'news', published: true }
]
array = array.map(t => t.published !== true ? { ...t, published: true } : t)

Related

Within an array of objects modify all previous objects to an object with a specific property

I have an array of objects, and according to a property inserted in one of them i would like to mark or select all the objects previous to that object container of the specific property
My array is in this way:
const arrX= [
{ status: '1' },
{ status: '2'},
{ status: '3', imHere: true },
{ status: '4' },
];
Then due to the property imHere on arrX[2], the positions arrX[0] and arrX[1] should be modified.
My expected result would be :
const arrX= [
{ status: '1',wasHere:true },
{ status: '2',wasHere:true},
{ status: '3', imHere: true },
{ status: '4' },
];
I know that the map method would be quite useful in this case, but canĀ“t find the way to check from index of object containing imHere backwards the former positions
One approach is to use .findIndex() and .map():
const arrX= [{ status: '1' }, { status: '2'}, { status: '3', imHere: true }, { status: '4'}];
const imHereIndex = arrX.findIndex(({imHere}) => imHere === true);
const result = arrX.map((val, index) => index < imHereIndex
? { ...val, wasHere: true }
: val
);
console.log(result);
Even if #Kinglish answer works like a charm I want to share another way to achieve your goal. This road is surely longer than Kinglish ones, never then less is a good alternative.
{ status: '4' },
];
function findProperty(arr) {
const hasProperty = arr.findIndex(el => Object.keys(el).includes('imHere'))
const addNewProperty = arr.map((el,i) => (i < hasProperty) ? {...el, wasHere: true} : el)
return addNewProperty
}
const updatedArray = findProperty(arrX)
console.log(updatedArray)
Here's one method for it using Array#reduce and a boolean to track whether we've encountered inHere
const arrX = [
{status: '1'},
{status: '2'},
{status: '3',imHere: true},
{status: '4'},
];
let found = false,
updated = arrX.reduce((b, a) => {
found = found || (a.hasOwnProperty('imHere') && a.imHere === true)
if (!found) a.wasHere = true;
return b.concat(a);
}, [])
console.log(updated)
A simple loop - breaking out of it when one of the objects contains imHere, otherwise adding in a wasHere property.
function update(arr) {
for (let i = 0; i < arr.length; i++) {
if (!arr[i].imHere) {
arr[i].wasHere = true;
} else {
break;
}
}
return arr;
}
const arr = [
{ status: '1' },
{ status: '2' },
{ status: '3', imHere: true },
{ status: '4' },
];
console.log(update(arr));

Find matching uniqueId between array with id's and array with objects and same id's

I have the following object and array that have matching Id's but because of a drag and drop feature a simple map without a find doesn't work, because they are not matching in order. I will explain.
I have this object (which is my updated values after a form submit)
data variable in my code below
{"we98Yt8JLyxkcJorf":"Kanye","yG6JiFaBBut6XgHpj":"2813348004","RcpDcF72K2aN9fub4":"kanye#usa.gov","ShBTee9MNxvRNG3XN":"123 White House Avenue","GSCZMMwscKh3ZaKix":"473 estate drive","Jmr7HoYmfXJWHMwmr":"2813348004"}
and I have this array with objects in them that correspond to the ids
cards variable in my code below
[{"inputType":"shortText","uniId":"we98Yt8JLyxkcJorf","label":"First Name:","value":"Kanye"},{"inputType":"phoneNumber","uniId":"yG6JiFaBBut6XgHpj","label":"Cell Phone Number","value":"2813348004"},{"inputType":"email","uniId":"RcpDcF72K2aN9fub4","label":"Work Email","value":"kanye#usa.gov"},{"inputType":"multipleChoice","uniId":"GSCZMMwscKh3ZaKix","label":"Preferred Method of Contact","value":"2813348004","options":[{"uniId":"poXf65zi8NDko5Je4","label":"Email"},{"uniId":"FmvYT4cbY8JotAaqA","label":"Cell Phone"}]},{"inputType":"Address","uniId":"ShBTee9MNxvRNG3XN","label":"Home Address","value":"123 White House Avenue"},{"inputType":"dropDown","uniId":"Jmr7HoYmfXJWHMwmr","label":"How did you find us?","value":"2813348004","options":[{"uniId":"EQj9MXdnaBjmCkAKZ","label":"Google"},{"uniId":"EbbhhqSd4K6sAsQ3T","label":"Referral"}]}]
Now I want to update the array with the new data, there is a uniqueId field on both of them that match, but I keep failing at trying to match them and update the array so I can submit that to the db in the format it needs ot be which is it's current state.
This is what I have tried thus far it returns undefined
const test = Object.keys(data);
console.log(test);
let testArray = [];
test.map((item) => {
let testArraySingle = cards.find((x) => {
x.uniId === item;
}).value;
testArray.push(testArraySingle);
});
console.log(testArray);
I have tried this also but it returns incorrect because it only matches it loops how many times of the array.length but doesnt keep checking, if that makes sense
const dataArray = Object.entries(data);
let newArray = [];
cards.map((card, i) => {
var checkId = dataArray[i][0];
let matchesArray = [];
if (card.uniId === checkId) {
const new_obj = { ...cards[i], value: dataArray[i][1] };
newArray.push(new_obj);
}
// }
});
Hope somebody can help with this. Thanks!
You could use combination of Array.prototype.filter() and Array.prototype.map() method to get your result. Traverse data keys using map and filter uniId by filter method and again use map to get the all the values.
const data = {
we98Yt8JLyxkcJorf: 'Kanye',
yG6JiFaBBut6XgHpj: '2813348004',
RcpDcF72K2aN9fub4: 'kanye#usa.gov',
ShBTee9MNxvRNG3XN: '123 White House Avenue',
GSCZMMwscKh3ZaKix: '473 estate drive',
Jmr7HoYmfXJWHMwmr: '2813348004',
};
const cards = [
{
inputType: 'shortText',
uniId: 'we98Yt8JLyxkcJorf',
label: 'First Name:',
value: 'Kanye',
},
{
inputType: 'phoneNumber',
uniId: 'yG6JiFaBBut6XgHpj',
label: 'Cell Phone Number',
value: '2813348004',
},
{
inputType: 'email',
uniId: 'RcpDcF72K2aN9fub4',
label: 'Work Email',
value: 'kanye#usa.gov',
},
{
inputType: 'multipleChoice',
uniId: 'GSCZMMwscKh3ZaKix',
label: 'Preferred Method of Contact',
value: '2813348004',
options: [
{ uniId: 'poXf65zi8NDko5Je4', label: 'Email' },
{ uniId: 'FmvYT4cbY8JotAaqA', label: 'Cell Phone' },
],
},
{
inputType: 'Address',
uniId: 'ShBTee9MNxvRNG3XN',
label: 'Home Address',
value: '123 White House Avenue',
},
{
inputType: 'dropDown',
uniId: 'Jmr7HoYmfXJWHMwmr',
label: 'How did you find us?',
value: '2813348004',
options: [
{ uniId: 'EQj9MXdnaBjmCkAKZ', label: 'Google' },
{ uniId: 'EbbhhqSd4K6sAsQ3T', label: 'Referral' },
],
},
];
const ret = Object.keys(data)
.map((x) => {
const tmp = cards
.filter((y) => y.uniId === x)
.map((z) => {
const obj = { ...z };
obj.value = data[x];
return obj;
});
return tmp;
})
.flat();
console.log(ret);

I need to get a value from an object inside an array

With Javascript how can I get the id of each object in this kind of object:
array = [
{ active: false, defaultTag:true, id: '507f191e810c19729de860ea', title: 'one' },
{ active: false, defaultTag:true, id: '507f191e810c19722de860ea', title: 'two' }
];
I need to fetch the id in order to check if the item already exists in the array whe a use intent to save the same object again.
Best regards
Americo
here you can get array of unique ids
var unique = [],
tmp, i = 0;
while(i < array.length){
unique.indexOf(tmp = array[i++].id) > -1 ? array.pop(i--) : unique.push(tmp)
}
console.log(unique);
Gather all your items under one object using Array.reduce. This will filter out duplicates
Use Object.values to get the values inside your object. The returned value is the filtered array
const array = [
{ active: false, defaultTag:true, id: '507f191e810c19729de860ea', title: 'duplicateOne' },
{ active: false, defaultTag:true, id: '507f191e810c19729de860ea', title: 'one' },
{ active: false, defaultTag:true, id: '507f191e810c19722de860ea', title: 'two' }
];
const removeDupsById = arr => Object.values(
arr.reduce((a, c) => ({...a, [c.id]: c}), {})
);
console.log(removeDupsById(array));

How to convert this mysql select return into one array

Is there anyway to convert this like the example below?
Convert this:
[
RowDataPacket { title: 'Code' },
RowDataPacket { title: 'Pizza' }
]
Into this:
['Code', 'Pizza']
I've provided you two possible solutions, in case if it's just an array of objects or an array of nested objects.
var arr = [{RowDataPacket: { title: 'Code' }}, {RowDataPacket: { title: 'Pizza' }}],
res = arr.map(v => v.RowDataPacket.title);
console.log(res);
var arr = [{ title: 'Code' }, { title: 'Pizza' }],
res = arr.map(v => v.title);
console.log(res);
Create a new array
var newArr = [];
And then push each item into the array
result.forEach(function(obj){
newArr.push(obj.title);
}

Tally Javascript object property values

I have several objects inside of an array in Javascript. The object looks like this:
model: [
{
category: 'Media',
value: '',
checked: false
},
{
category: 'Entertainment',
value: '',
checked: false
},
{
category: 'Music',
value: '',
checked: false
},
{
category: 'Theater',
value: '',
checked: false
}
]
I want to loop through this array of objects, and tally up the number of checked: true values there are. If all of them equal true, I want to run a function. How do I go about seeing if all of the checked values are equal to true?
The easiest way to do this would be to use Array.prototype.reduce:
var aggregate = function (arr) {
return arr.reduce(function (p, c) {
return c.checked ? p + 1 : p;
}, 0);
}
if (aggregate(model) === model.length) {
// call your function
}
edit
As pointed out by #Bergi, it's faster to use the Array.prototype.every solution from the comments above, since .every terminates on the first instance the callback returns false:
var allChecked = function (arr) {
return arr.every(function (item) {
return item.checked;
});
}
if (allChecked(model)) {
// call your function
}
Although, if you're after performance, it's even faster to use a for-loop:
var allChecked = function (arr) {
for (var i = arr.length; --i;)
if (!arr[i].checked) return false;
return true;
}
As Xufox and royhowie suggested, every() is the optimum choice:
obj.model.every(val=>val.checked); // ES6
obj.model.every(function(val){ return val.checked; }); //ES5.1+
If you wanted to play with prototypes:
Array.prototype.countWhenField = function(field){this._field=field; return this};
Array.prototype.isEqualTo = function(val){
var arr = this,
fld = this._field;
// using reduce() here as an example, but can use every()
return arr.reduce(function (prev, curr) {
return curr[fld] == val ? prev + 1 : prev;
},0);
};
var obj = {
model : [
{
category: 'Media',
value: '',
checked: true
},
{
category: 'Entertainment',
value: '',
checked: true
},
{
category: 'Music',
value: '',
checked: false
},
{
category: 'Theater',
value: '',
checked: true
}
]
};
console.log(
obj.model.countWhenField('checked').isEqualTo(true), // 3
obj.model.length // 4
);
Advice is to stay away from prototypes for various reasons (especially don't prototype the base Object or Array class). The above is a horrible example and should not by any means be used in production code (too many issues to point out in a short time).
It is important to note that the above is only a quick example to demonstrate how you can make something more english (e.g., arr.countWhenField('checked').isEqualTo(true) == arr.length).

Categories