How to insert object via push method in javascript? - javascript

I cannot add an object via push method to javascript, my code is:
arrObj = [
{
name: "Krunal",
age: 26,
},
{
name: "Ankit",
age: 24,
},
];
function onAdd() {
return CART.push(arrObj);
}
What is the reason ?

if CART is an array, you should use .concat() instead
const newArray = CART.concat(arrObj)
as arr1.concat(arr2) will concat two arrays and return the result
whereas arr1.push(arr2) will result in an array within an array

Related

How to parse an array of objects to a list of strings? (Javascript)

In my Vue application I have a list of objects looking like this:
const arr = [
{
id: 1,
name: 'Max',
grade: 3
},
{
id: 2,
name: 'Lisa',
grade: 2
}
];
Now I want every object in this array to be a single string for itself. I know there is JSON.stringifty but this makes my whole array to a string and not every single object.
So the result should be something like:
const arr = [
"{id:1,name:'Max',grade:3}",
"{id:2,name:'Max',grade:3}"
];
That would be
const myJsonArr = arr.map((v) => JSON.stringify(v))
you can try it
let array = arr.map(item=>JSON.stringify(item))

From array of Object , get array of only matched key value

Suppose I have an array of object:
var students = [{name: 'Nick',achievements: 158,points: 1473}, {name: 'Nick',achievements: '175',points: '16375'},
{name: 'Ramon',achievements: '55',points: '2025'}];
I want to extract points from name Nick only in an array.
Like if (name=='Nick), O/P should be [1473,16375]
I tried:
var arrayPoints = students.map(function (el) {
if(el.name=='Nick'){
return el.points
}
});
But it gives me o/p:
console.log(arrayPoints)
[1473,16375,undefined] o/p
A look to the methods:
Array#map returns a (new) value for each element.
Array#filter returns exactly the element if the return value of the callback is truthy
You could take two steps, one for filtering the items and another to get the values from.
const
students = [{ name: 'Nick', achievements: 158, points: 1473 }, { name: 'Nick', achievements: '175', points: '16375' }, { name: 'Ramon', achievements: '55', points: '2025' }],
arrayPoints = students
.filter(student => student.name === 'Nick')
.map(student => student.points);
console.log(arrayPoints);
If Array#flatMap is implemented, you could take a single loop and filter and return a value.
The empty array has no items and this array is a neutral value which does not turn up in the result array.
const
students = [{ name: 'Nick', achievements: 158, points: 1473 }, { name: 'Nick', achievements: '175', points: '16375' }, { name: 'Ramon', achievements: '55', points: '2025' }],
arrayPoints = students
.flatMap(student => student.name === 'Nick'
? student.points
: []
);
console.log(arrayPoints);
For single loop result without undefined. You could do with Array#reduce
students.reduce(function (acc,el) {
if(el.name=='Nick'){
acc.push(el.points)
}
return acc
},[]);
You can use reduce for that:
The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value.
So You can use it and check if the name is indeed Nick (el is the currentValue).
if so then push the points to the accumulator (which is arr).
[] represent the initialValue passed to the reduce function.
var arrayPoints = students.reduce((arr, el) =>
(el.name === 'Nick' && arr.push(el.points), arr), [])
You can find more info regarding reduce here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

convert an object literal into an array

I have an array object here:
var obj = {
name: 'Chris',
age: 25,
hobby: 'programming'
};
I need a function that will convert an object literal into an array of arrays even without knowing the key or the value like this:
[['name', 'Chris'], ['age', 25], ['hobby', 'programming']]
So I created a function to do that. However I am not sure where to start to enable me to merge them.
function convert(obj) {
var array = [];
}
convert(obj);
Any help?
using Object.keys() and Array#map()
var obj = {
name: 'Chris',
age: 25,
hobby: 'programming'
};
function convert(obj) {
return Object.keys(obj).map(k => [k, obj[k]]);
}
console.log(convert(obj));
You can do this:
1. Iterate through the object
2. Push the key and value in to array and then puh that array into answer array
var obj = {
name: 'Chris',
age: 25,
hobby: 'programming'
};
var ans = [];
for(var i in obj) {
ans.push([i, obj[i]]);
}
console.log(ans);
You can use Object.keys to extract all property names:
var arr=[];
Object.keys(obj).forEach(function(key){
arr.push([key, obj[key]]);
})

Get first object from array

I am trying to create an array which will hold just the Name elements from this array:
var array = [{Name: "steve"}, {Age: 18}, {Location: "Uk"}];
I am new to JavaScript and I am not sure how this would be done.
Here is a good read to understand how object works: http://www.w3schools.com/js/js_objects.asp
if you really want the name first element from this array just use
array[0]
If you want an array of just the objects that have a Name key, you can use Array.prototype.filter().
This will return a two-item array [{Name: "steve"}, {Name: "conor"}]:
var array = [{Name: "steve"}, {Age: 18}, {Location: "Uk"},
{Name: "conor"}, {Age: 18}, {Location: "Uk"}];
var names = array.filter(function(obj) {
if ('Name' in obj) {
return true;
} else {
return false;
}
});
If you want an array of just the Name values of just the objects that have a Name key, you can use Array.prototype.filter() and Array.prototype.map() together.
This will return a two-item array ["steve", "conor"]:
var array = [{Name: "steve"}, {Age: 18}, {Location: "Uk"},
{Name: "conor"}, {Age: 18}, {Location: "Uk"}];
var names = array.filter(function(obj) {
if ('Name' in obj) {
return true;
} else {
return false;
}
}).map(function(obj) { return obj['Name']; });
Either way, you may want to take another look at the structure of your array. It probably makes more sense to group your "people" so that each one is a single object, something like:
[{name: "steve", age: 18, location: "Uk"}, {name: "conor", age: 18, location: "Uk"}]
A new feature that javascript has is array destructuring!
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
It removes all the complexity of using a custom function, or using the hard coded 0 index (seems like a code smell).
Just destructure the value into a variable. If the array is empty the value will be undefined.
const arr = ["one", "two", "three"];
const [first] = arr;
I know this is an older post but I have a pretty cool solution that gets key from the array and then uses that to return the first item, or alternatively last, the current code is es6 but its simple to convert to es5.
Array.prototype.first = function () { let k = Object.keys( this ); return this[ k[ 0 ] ]; }
//re for last...
Array.prototype.last = function () { let k = Object.keys( this ); return this[ k[ k.length - 1 ] ]; }
To change to es5 use var rather than let.
Reason for this prototype is to make sure that regardless or the index system used will always return first element or the last element...

Issue on having an array in an JavaScript object

Can you please let me know if it is possible to pass an array into a JavaScript object like this?
var content = {
item1: "John",
item2: "Doe",
item3: { "item3_1", "item3_2", "item3_3" }
}
console.log(content);
Can you please let me know how I can access or update the items, or if not, can you please let me know how I can create a data format (Array of Array for example) to store these data?
The syntax for defining an array on a JavaScript object looks like this:
var content = {
item1: "John",
item2: "Doe",
item3: ["item3_1", "item3_2", "item3_3"]
};
You're not "passing" the array into the object, you're simply defining one of the properties to be an array. Any nested data inside that would take the same form that an object or another array would:
var foo = {
arr: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
};
The important thing to remember is that you use '{}' for object syntax, and '[]' for array syntax. You can also have objects inside that array:
var bar = {
obj_arr: [
{
name: "Tim",
age: 14,
},
{
name: "Bob",
age: 36
},
{
name: "Sue",
age: 73
}
]
};
To access one of the individual elements from the array property, use this syntax:
content.item3[0] for "item3_1"
content.item3[1] for "item3_2"
or, alternatively:
content["item3"][0] for "item3_1"
content["item3"][1] for "item3_2"
although this syntax is less common when the property name is known ahead of time. To loop through the items in that array, you can use a for loop:
for (var i = 0, l = content.item3.length; i < l; i += 1) {
console.log(content.item3[i]);
}
This is how you would console.log the items out - if you wanted to do something else with them, you would need to substitute that action for the console.log call.
Here's an updated fiddle that does what I believe you're looking for: http://jsfiddle.net/qobo98yr/5/
This is the code for printing everything out in the content object to the console:
var outputString = "";
for (var prop in content) {
outputString += (content[prop] + " ");
}
console.log(outputString);
You content variable is an object that contains:
item1: String
item2: String
item3: array
var content = {
item1: "John",
item2: "Doe",
item3: { "item3_1", "item3_2", "item3_3" }
}
If item3 is an array then is should use the array notation
var content = {
item1: "John",
item2: "Doe",
item3: ["item3_1", "item3_2", "item3_3"]
}
Now you can pass this object around and call its fields like that:
function print(obj) {
var fname = obj.item1;
var lname = obj.item2;
var array = obj.item3;
alert(array.toString());
}
where call to the function will look like
print(content);

Categories

Resources