Array acting weird? [duplicate] - javascript

This question already has answers here:
Javascript Console Log reporting object properties incorrectly
(1 answer)
Weird behavior with objects & console.log [duplicate]
(2 answers)
Closed 5 years ago.
I've got the following code:
$(document).ready(function(){
var array = [{"x": 0}];
array[0] = {"x": 10};
console.log(array);
array[0] = {"x": 20};
console.log(array);
});
With this I expect the output in the console to be:
[
{
0: {"x": 10}
}
]
[
{
0: {"x": 20}
}
]
But instead it is:
[
{
0: {"x": 20}
}
]
[
{
0: {"x": 20}
}
]
Does anyone have any idea why? Am I missing something?
JSFiddle: https://jsfiddle.net/6nfdmt91/

try:
$(document).ready(function(){
var array = [{"x": 0}];
array[0] = {"x": 10};
console.log(array);
array[0].push({"x": 20});
console.log(array);
});
Using Array.push() will "push" a new element.

Related

Mapping keys into objects with Javascript [duplicate]

This question already has answers here:
How to transpose a javascript object into a key/value array
(11 answers)
Closed 8 months ago.
This is the object I have:
years = {1924:2, 1934: 10, 2010: 4}
I would like to transform this into:
years = [{year: 1924, items: 2}, {year: 1934, items: 10}, {year: 2010, items: 4}]
This is the code I came up with so far (which obviously doesn't work):
var years2 = {};
for (var i = 0; i < years.length; ++i) {
years2.push({ years: [$key] })
};
I am stuggling to find the right way to access the unnamed keys and map these into their own objects.
(I am still learning JS and I know this is basics, but somehow cannot get my head around it.. )
You can create key value pairs from the object with Object entries and map them to new array
const years = {1924:2, 1934: 10, 2010: 4}
const ans = Object.entries(years).map(([key,value]) => {
return {year: key, items: value}
})
console.log(ans);
You can get entries, then convert to object with map
const years = {1924:2, 1934: 10, 2010: 4}
const result = Object.entries(years).map(([year, items]) => ({year: year, items: items}))
console.log(result)

JavaScript Array of Objects to Array of Arrays Grouped by Object Prop Value [duplicate]

This question already has answers here:
How can I group an array of objects by key?
(32 answers)
Closed 2 years ago.
This is somewhat complex for me to put into words properly, so I'll just drop an example of what I'm trying to do in terms of input and expected output below. I've tried a few things but they seem to be way more complex than needed, result in duplication issues, or flat out don't work. Thanks ahead of time for any help people can provide. And if there's already a post that answers this question, I am sorry and I'll gladly take that link - as I said, it's difficult to put this into words.
Input: Array of Objects
Ex:
[
{prop: 1},
{prop: 1},
{prop: 2},
{prop: 3},
{prop: 2}
]
OUTPUT: Array of arrays where all objects with some matching property are grouped.
Ex:
[
[{prop: 1}, {prop: 1}],
[{prop: 2},{prop:2}],
[{prop:3}]
]
Simple reduce loop with an object
var arr = [
{prop: 1},
{prop: 1},
{prop: 2},
{prop: 3},
{prop: 2}
]
const result = Object.values(arr.reduce((acc, item) => {
acc[item.prop] = acc[item.prop] || [];
acc[item.prop].push(item);
return acc;
}, {}));
console.log(result);

How to add an array to an array object [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
How do I make object1 to object2? It's a JSON type from an API so I can't just manually put the value of array inside the object. Z is actually var z = [4,5,6]; a completely separate array.
var object1 = {
value:[{
"x": "apple",
"y": [1,2,3]
}]
};
var object2 = {
value:[{
"x": "apple",
"y": [1,2,3],
"z": [4,5,6]
}]
};
You can just access the array and update it:
const updateObjectAtIndex = (arr, index, newData) => {
const clone = [...arr];
const result = {
...clone[index],
...newData
};
clone[index] = result;
return clone;
}
var object1 = {
value:[{
"x": "apple",
"y": [1,2,3]
}]
};
var object2 = {
...object1,
value: updateObjectAtIndex(object1.value, 0, {z: [4, 5, 6]})
}
console.dir(object2)
The Object.assign() method is used to copy the values of all
enumerable own properties from one or more source objects to a target
object. It will return the target object.
var object1 = {
value:[{
"x": "apple",
"y": [1,2,3]
}]
};
var object2 = {
value:[{
"x": "apple",
"y": [1,2,3],
"z": [4,5,6]
}]
};
const object3 = Object.assign(object1, object2);
console.log(object3);

Using a variable in an JSON query

I am trying to write a function that can take a field name as an argument and return an array of corresponding values from a bit of JSON.
Example object:
var myObject = [
{"x": 10, "y": 10},
{"x": 20, "y": 10},
{"x": 20, "y": 20},
{"x": 10, "y": 20}
];
My function looks something like this:
function getValues(desiredValue) {
var values = [];
for (i = 0; i < myObject.length; i++) {
values[i] = myObject[i].desiredValue;
}
return values;
}
getValues(x);
Ideally, I would have the argument x passed to the getValues which, instead of looking for a field name called desiredValue would look for a field name called x.
The returned array should look like this:
[10,20,20,10]
As the problem with this code is obvious, how can I get the desired result?
Also, I am trying to avoid unnecessary dependencies, so please don’t give me any JQuery unless absolutely necessary.
You can use map() to return desired result.
var myObject = [
{"x": 10, "y": 10},
{"x": 20, "y": 10},
{"x": 20, "y": 20},
{"x": 10, "y": 20}
];
function getValues(desiredValue) {
return myObject.map(e => e[desiredValue]);
}
console.log(getValues('x'))
You actually need to parse the given JSON string (not the array that you have given here) by using JSON.parse(). See: http://jsbin.com/kevoqe/edit?js,console
a simple utility
//also accepts a path like "foo.bar.baz"
//returns undefined if path can't be resolved
function fetch(path){
var keys = path.split(".");
return function( target ){
for(var t = target, i = 0; i < keys.length; t = t[ keys[ i++ ] ])
if(t == null) return void 0;
return t;
}
}
and it's usage
var myObject = [
{"x": 10, "y": 10},
{"x": 20, "y": 10},
{"x": 20, "y": 20},
{"x": 10, "y": 20}
];
var result = myObject.map( fetch("y") );
this version is a bit more flexible than one hardwired with Array.map() because it can easily be composed with other functions.
Although, especially in this particular case, this already is a little bit of overkill. here you can easily write:
var result = myObject.map(pt => pt.y);
you can't get any shorter and simpler. Or if for some reason the property really is dynamic, you'll have some variable containing it:
var dynamicPropertyName = "y";
//...
var result = myObject.map(pt => pt[ dynamicPropertyName ]);
Use array map method to do manipulation in an array of objects.
Try this code :
var myObject = [
{"x": 10, "y": 10},
{"x": 20, "y": 10},
{"x": 20, "y": 20},
{"x": 10, "y": 20}
];
var output = getValues("x");
console.log(output);
function getValues(desiredValue) {
return myObject.map(function(item) {
return item[desiredValue];
});
}
Output :
Working fiddle : https://jsfiddle.net/ffyjyzjb/

Problem of serializing javascript object to JSON string

My question is sort of stupid that why
JSON.stringify({"annotation": [{"x":1, "y":2}, {"x":1, "y":2}]})
does not return
{"annotation": [{"x": 1, "y": 2}, {"x": 1, "y": 2}]}
but returns
{"annotation":"[{\"x\": 1, \"y\": 2}, {\"x\": 1, \"y\": 2}]"}
and how can I get the first output?
Are you using Prototype? This question may be related:
JSON.stringify() array bizarreness with Prototype.js

Categories