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);
Related
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 1 year ago.
Improve this question
I have 2 arrays already setup within the js:
varDepth:
[0.5, 1.75, 2.38, 2.74, 2.89]
varMins:
[0, 1, 2, 3, 4]
I'm looking to create an object (chartData1) to push and this is the format of the array:
chartData1.push({'x': varDepth[i][0], 'y': varMins[i][1]});
But I cannot get this to work, I think I'm missing the setting up of the object, Any assistance would be greatly appreciated. Thanks!
Since you're trying to create multiple objects who's data are from the same indexes in both arrays; you can;
Loop over one of the arrays (I'm using map() so we can return the created objects into an array)
Add value to a new object
Add value of the other array, on the same index
const depths = [ 0.5, 1.75, 2.38, 2.74, 2.89 ];
const mins = [ 0, 1, 2, 3, 4 ];
let result = depths.map((depth, index) => ({ x: depth, y: mins[index]}))
console.log(result);
[
{
"x": 0.5,
"y": 0
},
{
"x": 1.75,
"y": 1
},
{
"x": 2.38,
"y": 2
},
{
"x": 2.74,
"y": 3
},
{
"x": 2.89,
"y": 4
}
]
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
having this type of data
{
"time_1": 20,
"time_2": 10,
"time_3": 40,
"time_4": 30
}
and expected result
[
{
"key1": "time_1",
"key2": 20,
},
{
"key1": "time_2",
"key2": 10,
},
{
"key1": "time_3",
"key2": 40,
},
{
"key1": "time_4",
"key2": 30,
}
]
How to convert object to array using JavaScript? I have updated my question.
You could use the Object.keys() methods to iterate over your object and then use the Array.map() method to transform your object to the array structure you need.
var data = {
"0": "value1",
"1": "value2"
}
var newData = Object.keys(data).map(key => ({
[key]: data[key]
}))
console.log(newData)
--Update--
You would simply need to change the object being returned from the callback function passed to the .map() method.
var data = {
"time_1": 20,
"time_2": 10,
"time_3": 40,
"time_4": 30
}
var newData = Object.keys(data).map(key => ({
"key1": key,
"key2": data[key]
}))
console.log(newData)
given data
const data = {
"time_1": 20,
"time_2": 10,
"time_3": 40,
"time_4": 30
}
get all keys of data object
const KeysOfData = Object.keys(data);
get expected output like this - [
{
"key1": "time_1",
"key2": 20,
},
]
const result = KeysOfData.map(key => {
const value = data[key]
return {
key1: key,
key2: value
}
});
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have raw json from file .csv like
[{
"A": "CustomerCode",
"B": "Country",
"C": "CountryCode"
},
{
"A": "C101",
"B": "AUS",
"C": "AUS01",
},
{
"A": "C102",
"B": "AUS",
"C": "AUS02",
}]
How can I could remove first element of array and change key name of array object like that
[{
"CustomerCode": "C101",
"Country": "AUS",
"CountryCode": "AUS01",
},
{
"CustomerCode": "C102",
"Country": "AUS",
"CountryCode": "AUS02",
}]
You could use .map() with Object.entries() and Object.fromEntries() to create new objects with keys from the first object in your array like so:
const arr = [{A:"CustomerCode",B:"Country",C:"CountryCode"},{A:"C101",B:"AUS",C:"AUS01"},{A:"C102",B:"AUS",C:"AUS02"}];
const prop_map = arr.shift();
const res = arr.map(o =>
Object.fromEntries(
Object.entries(o).map(([k, v]) => [prop_map[k], v]))
);
console.log(res);
Above, .shift() gets the first object from the array as a mapping object to reference later. The .map() is then in charge of mapping (ie converting) each object to a new modified object. The new modified object is defined by what the internal function of .map() returns. In this can it takes the entries (a key-value pair array [[key, value]]) of objects and uses another .map() method. This .map() maps each key-value pair array to a new key-value pair array. However, the key now is defined by its associated value in the prop_map (the object we extracted at the beginning using .shift()). Now that we have an array of key-value pair arrays where each key is a value from the prop_map, we can use Object.fromEntries(), which converts this key-value pair array into an object. This new object is returned by the .map() being applied to the arr, which produces the final result.
Do note that Object.fromEntries() does have limited browser compatibility, however, you can use a polyfill if need be.
You can remove the first item from the array then map over the array.
let data = [{
"A": "CustomerCode",
"B": "Country",
"C": "CountryCode"
},
{
"A": "C101",
"B": "AUS",
"C": "AUS01",
},
{
"A": "C102",
"B": "AUS",
"C": "AUS02",
}];
// Remove first item in array
data.shift();
let newData = data.map(({A, B, C}) => ({
CustomerCode: A,
Country: B,
CountryCode: C
}));
console.log(newData);
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 5 years ago.
Improve this question
I can ordering a-z using the .sort() method in javascript, but I would get a JSON like this: (With a "A-Z" index containing the result)
data: {
"A": [
{
"name": "Anh Tuan Nguyen",
"age": 28
},
{
"name": "An Nguyen",
"age": 20
},
],
"Z": [
{
"name": "Zue Dang",
"age": 22
},
{
"name": "Zoom Jane",
"age": 30
},
]
}
var names = [{name:"a1"},{name:"a2"},{name:"b1"},{name:"b2"}.....];
var data = {};
for (var i = 0; i < names.length; i++) {
var n = names[i].name.subStr(0,1);
if (data[n] == null)
data[n] = [];
data[n].push(names[i]);
}
There is no way to sort a JSON data structure, however, we can do it by using the following process:
Get your data keys with Object.keys(myResults.data)
Sort you keys
Create a reduce function to transform your ordered keys into an ordered object
The snippet is here, I hope it helps:
var myResults = {
data: {
C: [
{
"name": "Kevin Doe",
"age": 22
}
],
A: [
{
"name": "Alex Doe",
"age": 31,
}
],
B: [
{
"name": "Boris Doe",
"age": 22
},
{
"name": "Birdo Doe",
"age": 30
},
]
}
};
var originalData = myResults.data;
// 1. get the keys
var dataKeys = Object.keys(originalData);
// 2. sort the keys
var sortedKeys = dataKeys.sort();
// 3. create the object again
var orderedData = sortedKeys.reduce(function(result, key) {
return Object.assign(
{},
result,
{ [key]: myResults.data[key] }
);
}, {});
document.getElementById('original').innerHTML = JSON.stringify(originalData);
document.getElementById('sorted').innerHTML = JSON.stringify(orderedData);
h3 {
margin: 0;
}
code {
display: block;
margin-bottom: 15px;
padding: 10px;
background-color: #f9f9f9;
}
<h3>Original Data</h3>
<code id="original"></code>
<h3>Ordered Data</h3>
<code id="sorted"></code>
JavaScript objects are not ordered. If you want to iterate over an object's properties, you can sort the keys and then retrieve your values:
const result = {
data: {
Z: [],
F: [],
A: [],
D: []
}
};
Object
.keys(result.data)
.sort()
.map(key => console.log(key, result.data[key]));
UPDATE:
Exist a JavaScript library that make It possible: Lodash Utilities (https://lodash.com/docs/4.17.4). Contain methods for .sort() JSON (no Arrays) and a method to obtain the JSON for I asked in this question. I only did this:
//First, order my JSON alphabetically with _.sortBy method (I can even order by a nested property in my JSON)
var order = _.sortBy(require('./names'), function (el) { return el.name });
//Second, I group my order result by the first letter of my property 'name' in my JSON
var list = _.groupBy(order, (b) => b.name[0].toUpperCase());
This is my input:
[
{"name":"Mark"},
{"name":"Jul"},
{"name":"Alicia"},
]
This is my output:
[
"A": [
{
"name": "Alicia"
}
],
"J": [
{
"name": "Jul"
},
],
"M": [
{
"name": "Mark"
},
]
I hope this help to somebody!
Here is my Javascript code:
var subRow = [];
var rowarr = [];
subRow.push({ v: "Jay" });
subRow.push({ v: "Ram" });
rowarr.push({ c: subRow });
subRow.length = 0;
subRow.push({ v: "Jay1" });
subRow.push({ v: "Ram1" });
rowarr.push({ c: subRow });
console.log(JSON.stringify(rowarr));
The output is:
[{
"c": [{
"v": "Jay1"
}, {
"v": "Ram1"
}]
}, {
"c": [{
"v": "Jay1"
}, {
"v": "Ram1"
}]
}]
The expected output is:
[{
"c": [{
"v": "Jay"
}, {
"v": "Ram"
}]
}, {
"c": [{
"v": "Jay1"
}, {
"v": "Ram1"
}]
}]
Can anyone explain why it so?
Arrays are handled by reference.
subRow.length = 0; erases the contents of the array.
rowarr then contains two pointers to the same array (which only has the content in it that you put there after emptying it)
Change subRow.length = 0; to subRow = [] to work on a new array instead of modifying the existing one.
subRow points to an object. When you push it onto rowArr you create a reference to that object. You push it twice, that's two references to one object. When you edit subRow both references to the object see the changes, so you've trampled all over the old contents of the object - they are not stored anywhere else, so they are completely lost. You need to create a brand new object instead of editing the old object.