what would be the result of my code ? I am expecting to have as result one single array of length 1 , I want to output only values of d variable that haven't been updated in my var2 variable but I get an array of length 2 , I want to have output
{name : "david", age : 23, day : 23}
const d = [{name : '',age : '',day :23}]
const var2 = [...d, { name : 'david', age : 22}]
console.log(var2)
You are not using the spread operator correctly. You should use it to merge all elements of d[0] with an object containing your updated values.
const d = [{name : '',age : '',day :23}]
// for d containing only one element
const var2 = [{...d[0], name : 'david', age : 22}]
// will result in [{name: '', age: '', day: 23, name: 'david', age: 22}] and be merged by keeping the right-most value
// for all elements in d
const var3 = d.map(el => {
return {...el, name : 'david', age : 22}
})
console.log(var2)
console.log(var3)
Think of it this way:
d is an array of objects
{ name : 'david', age : 22} is an object literal
When you use the spread operator on d, you are telling it to take each object in d and place it into var2, then at the end, append the { name : 'david', age : 22}.
So the result would be an array with all the items you had in d + the object literal { name : 'david', age : 22}.
To get your expected result {name : "david", age : 23, day : 23} merge two objects like shown below.
merge Object like {...object1, ...object2}
const d = [{name : '',age : '',day :23}]
const var2 = {...d[0], ...{ name : 'david', age : 22}}
console.log(var2)
Spread operator you use in line 2 is used when all elements from an object or array need to be included in a list of some kind.
Basically what happens in your code ->
Array d has 1 item, so when you try to define var2 it takes all elements from array d ( 1 in our case ) and add { name : 'david', age : 22} to it.
In result you get array of two items.
For example:
const array1 = [1, 2, 3]
const array2 = [...array1,4, 5]
// array2 now is [1, 2, 3, 4, 5]
console.log(array2)
the (...) is Array/Object spread operator js spread operator
What the code above does, is to spread over the d object and get all its properties, then overwrite the existing properties with the ones we’re passing. It copies the properties of the d object, over to the newly created object. So you are getting this output. Try the below code:
<script>
const d = [{name : '',age : '',day :23}]
const var2 = [{...d[0], name : 'david', age : 22}]
console.log(var2)
</script>
You can also achieve the same using below code
<script>
const d = {name : '',age : '',day :23}
const var2 = {...d, name : 'david', age : 22}
console.log(var2)
</script>
It will override the name and age
Related
I have an array of data, and an array of objects:
const data = ['1', '2', '2'];
const objlist = [{name : 'dummy'} , {name: 'new'}, {name : 'news'}, {name : 'place'}, ...]; // 5 objects
I want to chunk the objects in objlist by the numbers in data so that I get the follow result:
result = [
[{name:'dummy'}],
[{name:'new'}, {name:'news'}],
[{name : 'place'}, ...]
]
As you can see, it should be of the form:
[[{obj1}], [{obj2}, {obj3}], [{obj4}, {obj5}]]
You could push sliced parts to the result.
let array = [1, 2, 2],
objlist = [{ name: 'dummy' }, { name: 'new' }, { name: 'news' }, { name: 'place' }, { name: 'place' }],
result = [],
i = 0,
j = 0;
while (j < array.length) {
result.push(objlist.slice(i, i += array[j++]));
}
console.log(result);
You can loop through your array of numbers and for each number n use .splice(0, n) to get an array chunk from your array of objects. This will modify the array in-place, allowing your next .splice() to get the next consecutive object. For each .splice() you perform, you can .push() this into a resulting array.
See example below:
function partition([...arr], chunks) {
const res = [];
for(const n of chunks)
res.push(arr.splice(0, n)); // +n to turn the string number into a number (splice will do this conversion for you but you can take care of it explicitly as well)
return res;
}
const chunkArr = ['1', '2', '2'];
const arr = [{ name : 'dummy' }, {name: 'new' }, { name : 'news'},{name : 'place'}, {name : 'foo'}];
console.log(partition(arr, chunkArr));
Above I'm using partition([...arr], chunks) which uses the destructuring assignment syntax to perform a shallow copy of your input array. This way when you modify it inside your function using .splice(), it won't change the passed-in array.
I've got this array of json objects with these data:
let data = [
{"id_player_team" : 1, "name" : "Jose", "t2p_conv": 3, "t3p_conv": 5},
{"id_player_team" : 2, "name" : "Jesus", "t2p_conv": 2, "t3p_conv": 1},
{"id_player_team" : 3, "name" : "Maria", "t2p_conv": 3, "t3p_conv": 0},
{"id_player_team" : 4, "name" : "Irene", "t2p_conv": 4, "t3p_conv": 2},
{"id_player_team" : 5, "name" : "Carmen", "t2p_conv": 1, "t3p_conv": 2},
];
I want to get the result of the addition of key "t2p_conv". To do this, I use reduce function of javascript, like this:
let sumt2p = data.reduce((acc, item) => {
return acc + item.t2p_conv;
});
console.log("Result: " + sumt2p);
When I try to show the value of sumt2p I've got this result:
Result: [object Object]2341
How is possible that? Am I doing something wrong?
When you're picking out a property like that, you need to supply the second argument to reduce to provide a seed value for acc parameter:
let sumt2p = data.reduce((acc, item) => {
return acc + item.t2p_conv;
}, 0);
// −−^^^
If you don't supply the seed, the first call to your callback uses the first two entries in the array. Since you're using + on an object (the first object in acc), it gets converted to a string. :-)
This is one of the many reasons that reduce is usually more complicated than necessary. Here, for instance, a simple loop, perhaps with destructuring, does the job:
let sumt2p = 0;
for (const {t2p_conv} of data) {
sumt2p += t2p_conv;
}
I would like to push the age attribute from items to an ages array
f.e.
items =[{name : "asd", age : "23"},
{name : "asd2", age : "34"}]
to an array:
ages = [ 23,34]
If you got it right then you can use .map to get all the values corresponding to key age.
var items =[{name: "asd", age: "23"}, {name: "asd2", age: "34"}];
var data = items.map(({age}) => age);
console.log(data);
I'm parsing a JSON message which looks something like:
{
staff : [
{name : 'John', department : 'Math'},
{name : 'Sally', department : 'Science'},
],
students : [
{name : 'Bob', department : 'Law'},
{name : 'Lisa', department : 'IT'}
]
}
From which I'd like to pull out an array of each separate value.
i.e.
names -> ['John', 'Sally', 'Bob', 'Lisa']
At the moment I'm doing something like
var names = [];
msg.staff.forEach(function(e) { names.push(e.name) })
msg.students.forEach(function(e) { names.push(e.name)})
This feels overly verbose, just wondering if there's a cleaner way to approach this (for every attribute). I'm already including lodash in this project.
You can use _.pluck to get the value of a property of each object in an array:
_.pluck(obj.staff.concat(obj.students), 'name')
Your instinct is right; you don't need a mutable array to do this with lodash.
_(obj).map().flatten().pluck('name').value();
This version works for any number of array values in o.
JSBin
Edit missed that you had lodash available, will leave this vanilla JS version here anyway.
You could use map to be more concise:
var directory = {
staff : [
{name : 'John', department : 'Math'},
{name : 'Sally', department : 'Science'},
],
students : [
{name : 'Bob', department : 'Law'},
{name : 'Lisa', department : 'IT'}
]
};
var names = directory.staff.concat(directory.students).map(function(person) {
return person.name;
});
If you don't know the individual key names before hand, you could do:
Object.keys(directory).map(function(key) {
return directory[key]
}).reduce(function(p,c){
return p.concat(c)
}).map(function(person) {
return person.name;
});
I didn't catch the requirement of getting an array of all values stored under each key, this should do it though:
Object.keys(directory).map(function(key) {
return directory[key];
}).reduce(function(p,c) {
return p.concat(c);
}).reduce(function(p, c) {
Object.keys(c).forEach(function(oKey) {
if(p[oKey]) p[oKey].push(c[oKey]);
else p[oKey] = [c[oKey]];
});
return p;
}, {});
This returns the following:
{
"name":["John","Sally","Bob","Lisa"],
"department": ["Math","Science","Law","IT"]
}
I have an existing JSON object that looks like so:
var data = {ID: 123, Name: "test"}
Now I want to add in an extra property and value to data based on the condition of an inline if statement. The result should look like the following:
data = {ID: 123, Name: "test", Surname: "again"}
The object above is based on the true condition, while the object below is based on the false condition:
data = {ID: 123, Name: "test", Lastname: "again"}
Note the change of the property name from Surname to Lastname.
So my question is, how do I add the new property and value into object based on the inline if condition?
I tried the following but obviously that did not work:
var data = {ID: 123, Name: "test"};
data = params.Region == 1 ? data.Surname = "again" : data.Lastname = "again"
Any help please
data[params.Region == 1 ? 'Surname' : 'Lastname'] = "again"
params.Region == 1 ? data.Surname = "again" : data.Lastname = "again"
You are assigning params.Region the value 1. Typo!
data = (params.Region === 1) ? data.Surname = "again" : data.Lastname = "again"