How to push new key value pair in existing javascript object? - javascript

I have defined array of object something like this:
this.choices = [
{
id: 0,
product: [{id:'0'}]
}
];
Now I want to insert new key-value pair in choices :
[
{
id: 10,
product: [{id:'5'}]
}
]
I tried to do it by push() method but I guess its for Array only. Please help me with same. Thank you so much in advance. :)
Also, Is it possible to push these key-pair value at certain index for these array of objects.

This should work,
this.choices.push({id: 10,product: [{id:'5'}]});

Since both examples are actually arrays containing objects, you should be using concat rather than push. ie;
this.choices = [
{
id: 0,
product: [{id:'0'}]
}
];
var newVal = [
{
id: 10,
product: [{id:'5'}]
}
];
this.choices = this.choices.concat(newVal);
In my example, to use push you'd need to do this.choices.push(newVal[0]) - many ways to approach it but basically, push is for individual values, concat is for arrays.

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 an array of objects, extract properties into multiple arrays (one per property)?

I have a JSON array of objects in JS that look something like this:
"data": [
{"name": "abc", "location": "NY", "value": 1234, "potato": "tomato", "someOtherProp": "prop1"},
{"name": "def", "location": "CA", ... etc}
{etc ...},
]
I'm creating a UI for filtering down some of these fields and want to create an array for each attribute with all the given values in the data.
I know this is possible using something like this:
let result = objArray.map(a => a.name);
But using this strategy, I have to run map once for every property. Is there any way to only go through the array once but create a separate array for each? (Or is there a better way in general for creating filter options for a UI?)
To clarify, for the array above, I'd want an array for "names" (containing "abc" and "def"), an array for "locations" (containing NY, CA, etc.) an array for "potato"s and "someOtherProp".
I appreciate any help!
Thanks
Loop through the array with .reduce(). In each iteration, loop through the keys of the object using Object.keys(), adding any unique values to an array of the same name.
This solution eliminates duplicate entries and works with any amount of properties.
const data = [{name: "abc", location: "NY"},{name: "def", location: "CA"},{name: "xyz", location: "TX"},{name: "zyx", location: "TX"}];
const getFiltersFromData = (data) => {
return data.reduce((out,obj) => {
Object.keys(obj).forEach(k => {
if (out[k] === undefined) out[k] = [obj[k]]; //Array doesn't exist yet - instantiate it
else if (!out[k].includes(obj[k])) out[k].push(obj[k]); //Array exists and this value isn't in it - add the value to it
});
return out;
}, {});
};
const filters = getFiltersFromData(data);
console.log(filters.name);
console.log(filters.location);
.as-console-wrapper, .as-console { height: 100% !important; max-height: 100% !important; top: 0; }
You could create the separate arrays from names, locations and values and then use map on the data array to push each attribute value to the arrays. You can do that vs. running map multiple times for each property:
var names = [];
var locations = [];
var values = [];
data.map((elt) => {
names.push(elt.name);
locations.push(elt.location);
values.push(elt.value);
});
Try with Object.entries
You can get something like this:
const obj = { foo: 'bar', baz: 42 };
console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ]

return a certain key:value of object

I have a array of object like this
AnArray: [
{ name: 'name1',
id: 123456,
arrayOfSomething: [[1], [2], [3]]
},
{ name: 'name2',
id: 123456,
arrayOfSomething: [[0], [2], [1]]
}
I need to push just the arrayOfSomething array in the result array, so I do:
SaveMyResult(){
this.result.push({
something:this.AnArray})
}
but it pushing me all the object data, How can I do ?
If you push AnArray, then yes, the result will be that AnArray is added to the end of your results array. If you don't want that, and you only want one property from each object, use the map method and concatenate the final array it creates:
this.result = this.result.concat(this.AnArray.map(({arrayOfSomething}) => ({arrayOfSomething})));
Here I've used a bit of destructuring to shorten the code, but it's basically going through every element of the array, pulling out its arrayOfSomething property, and replacing the element with a new object that contains only that property.

How to effeciently return a subarray by key

I have the following structure:
myArr: [
{
key1: 'foo',
myArr: [
{ a: 'blah' }
{ a: 'blah2'}
],
},
{
key1: 'foo2',
}
...More similar entries
];
I am looking for an efficient way to extract the sub arrays into a separate array. The sub arrays have the same key as the parent. The sub arrays may or may not exist.
I can iterate through them in a loop and manually add them to a new array if they exist.
I would prefer to use some sort of map/filter if it's possible to do in this particular case.
The result I am after is:
myArr: [
{ a: 'blah' },
{ a: 'blah2'},
{ a: 'blahN'}
],
A slick way to accomplish this would just be to reduce the initial array:
let result = myArr.reduce((a,b) => a.concat(b.myArr || []), []);
That starts with an empty array and just concats the selected property into it, resulting in a single array of objects. If the subarray is undefined or otherwise falsy, we can concat an empty array (which will not actually add anything to the original array)

Ember.js computed: Shortest way to return single object from array

Given an array of objects with ids:
array: [
{id: 3, value: 'foo'},
{id: 6, value: 'bar'},
{id: 9, value: 'baz'},
// ...
],
What is the shortest way to return a single object from the array that matches an id?
Keep in mind that the array can be undefined while the model is loading. In that case, the computed property should also return undefined.
This works:
_test : computed.filterBy('array', 'id', 6),
test : computed.alias('_test.firstObject')
But it is not pretty, using a temporary variable.
This is better:
test : computed('array.[]', function() {
let array = this.get('array')
if (array) return array.find(el => el.id == 6)
})
But it is not pretty, because it uses 4 lines.
Ember contains a lot of syntactic sugar, but I haven't figured out how to shrink this.
The methods filter and filterBy will reduce an array to just the list of items you're filtering to.
If you want a single item from the list, use find or findBy.
In your case, you'll use the following.
test: computed('array.[]', function() {
return this.getWithDefault('array',[])
.findBy('id',6)
})
When you're done, this.get('test') will return {id: 6, value: 'bar'}
More information can be found in the documentation for MutableArray

Categories

Resources