I've got an array of objects
var myArray = [{'id':'1','value':'firstValue'},{'id':'1','value':'secondValue'}, etc.]
I want to be able to extend the array later on in the code, so that I will have
var myArray = [{'id':'1','value':'firstValue', 'anothervalue':'anotherFirstValue'},{'id':'1','value':'secondValue', 'anothervalue':'anotherSecondValue'}, etc.]
Is there a way to do it without redefining myArray?
You can map the array, and add to each object:
var myArray = [{
'id': '1',
'value': 'firstValue'
}, {
'id': '1',
'value': 'secondValue'
}];
//later on
myArray = myArray.map(function(obj) {
obj.anothervalue = 'anotherFirstValue';
return obj;
});
console.log(myArray);
Related
My array in variable is:
"1": ["48": '1', "49": '2']
"2": ["51": '3', "52": '4', "53": '5', "54": '6']
"3": ["30": '7']
I've mentioned key and value here for the 2D array, I'm trying to convert this to JSON string. I tried JSON.stringify(arraydata), arraydata is the variable where the array is stored, but it makes the string empty, whereas array data is correct.
Edit:
This is how I'm adding array data:
var arraydata = new Array();
$('.classselector').each(function(){
let key1= $(this).data('key1');
let key2= $(this).data('key2');
if ( !Array.isArray(arraydata['"'+key1+'"']) ) {
arraydata['"'+key1+'"'] = new Array();
}
arraydata['"'+key1+'"']['"'+key2+'"'] = $(this).val();
});
The "array" quoted in your question is not valid JavaScript code. Maybe you had on object of objects instead? In that case the object can easily be converted into a JSON string:
const obj={"1": {"48": '1', "49": '2'},
"2": {"51": '3', "52": '4', "53": '5', "54": '6'},
"3": {"30": '7'}};
console.log(JSON.stringify(obj));
// in case you were really talking about
// a sparsely populated array of arrays,
// then the solution could look like this:
const arr=[];
arr[1]=[];
arr[1][48]='1';
arr[1][49]='2';
arr[2]=[];
arr[2][51]='3';
arr[2][52]='4';
arr[2][53]='5';
arr[2][54]='6';
arr[3]=[];
arr[3][30]='7';
console.log(arr);
console.log(JSON.stringify(arr));
See my comment above. Use objects instead of arrays!
Your corrected script could look something like this:
var arraydata = {};
$('.classselector').each(function(){
let key1= $(this).data('key1');
let key2= $(this).data('key2');
if ( !arraydata[key1] ) {
arraydata[key1] = {};
}
arraydata[key1][key2] = $(this).val();
});
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.
Say I have an object:
myObj = {
name: 'Luke',
age: 12,
height: '163cm',
weight: '60kg',
others: { one: '1', two: '2', three: '3'} // (Edited) Added one more key here :)
};
I want a copy of this object without certain keys to a new object in a way that the output is as below:
newObj = {
name: 'Luke',
age: 12,
one: '1',
two: '2'
};
I have seen examples of destructing but I wanted to know if it is possible with nested objects. Is something like this doable using destructuring or if not what would be the most efficient way to do this.
One way to achieve this with destructure-like syntax would be like this:
const myObj = {
name: 'Luke',
age: 12,
height: '163cm',
weight: '60kg',
others: { one: '1', two: '2', three : '3'}
};
const newObj = {
/* Copy over values from "myObj" to equivalent keys in "newObj" */
name : myObj.name,
age : myObj.age,
/* Spread keys "one" and "two" of the nested "others" object into "newObj" */
...({one, two} = myObj.others, {one, two})
}
console.log(newObj)
For completeness, an iife approach is possible. It works by creating an arrow function that takes as parameters keys you want to keep. In the function body, spread nested objects as desired.
const myObj = {
name: 'Luke',
age: 12,
height: '163cm',
weight: '60kg',
others: { one: '1', two: '2'}
};
const newObj = (
({name, age, others}) => ({name, age, ...others})
)(myObj);
console.log(newObj);
For the object of unknown depth you can try using recursion.
Create a function which takes an object and array of keys to be removed as arguments.
Create a helper(which takes 1 object as parameter) function inside main and create empty object.
Loop through the properties of obj using for..in.
check if key is not present in the array of keys to be removed then
Check if the value is object then call the function recursively
If its not object then add it to the result obj.
At last return the result object.
The code will convert the object of unknown depth to a plain object and you can also remove keys from nested objects.
const myObj = {
name: 'Luke',
age: 12,
height: '163cm',
weight: '60kg',
others: { one: '1', two: '2'}
};
const removed = ['height','weight','one'];
function removeKeys(obj,removed){
const res = {};
function helper(obj){
for(let key in obj){
if(!removed.includes(key)){
if(typeof obj[key] === "object"){
helper(obj[key]);
}
else res[key] = obj[key]
}
}
}
helper(obj)
return res;
}
const res = removeKeys(myObj,removed);
console.log(res)
I have a requirement where I need to populate array based on mapping of JSON object.
For e.g:
Suppose I have JSON object as shown below:
let columns = { 'name' :'value', 'id' : 1, 'age': 15}
And I want to create an array having value as shown below:
var values = [1, 15, value]; // id, age, name
I was able to create array of array as shown below:
var data = new Array();
var output = new Array();
let columns = [
{ 'name' :'value', 'id' : 1, 'age': 15},
{ 'name' :'value1', 'id' : 2, 'age': 18}
];
for(let i=0;i< columns.length; i++) {
for (let variable in columns[i]) {
data.push(columns[i][variable]);
}
output.push(data);
data = new Array();
}
console.log(output);
I am struggling to push value to array in order which I need. I tried by creating a mapping object but no success so far. Please let me know possible solution.
EDIT:
Thanks for the solution is there any way by which I can define the map function arguments and json object in variable. And replace it. Something like shown below:
let mapping {
columns : '{name, id, age}',
mapping : '[id, age, name]'
}
const result = columns.map((mapping.columns) => mapping.mapping);
You can use map() method with ES6 parameter destructuring and add properties to array in order you want.
let columns = [{ 'name' :'value', 'id' : 1, 'age': 15},{ 'name' :'value1', 'id' : 2, 'age': 18}];
const result = columns.map(({name, id, age}) => [id, age, name]);
console.log(result)
You can also remove the inner for loop and read data with the column names (or the JSON field names), So it becomes as follows.
var data = new Array();
var output = new Array();
let columns = [
{ 'name' :'value', 'id' : 1, 'age': 15},
{ 'name' :'value1', 'id' : 2, 'age': 18}
];
for(let i=0;i< columns.length; i++) {
data.push(columns[i]['id']);
data.push(columns[i]['age']);
data.push(columns[i]['name']);
output.push(data);
data = new Array();
}
console.log(output);
you can use Object.values() to get the every values from the object
var output = new Array();
let columns = [
{ 'name' :'value', 'id' : 1, 'age': 15},
{ 'name' :'value1', 'id' : 2, 'age': 18}
];
output = columns.map(item => Object.values(item))
console.log(output);
I have a project where in one instance I am returning an object that contains three separate arrays of objects.
Like so...
[
Array 1:[
{ key: value}
],
Array 2:[
{ key: value},
{ key: value}
],
Array 2:[
{ key: value},
{ key: value}
]
]
What I'm trying to do is take this multi array of objects and make it a single array containing the objects from all three.
I'm trying to do this using angular.forEach and loop through them and push them into a new array, but it's not working.
var newArray = [];
angular.forEach(result, function(value, key){
newArray.push(value);
});
return newArray;
Could really use some advice on this one!
Thanks!
You can use concat() and spread syntax.
var arr = [[{ key: 'value'}],[{ key: 'value'},{ key: 'value'}],[{ key: 'value'},{ key: 'value'}]]
var result = [].concat(...arr);
console.log(result)
You can use reduce method, which accepts a callback provided function.
var arr = [[{ key: 'value'}],[{ key: 'value'},{ key: 'value'}],[{ key: 'value'},{ key: 'value'}]]
var array = arr.reduce(function(obj,item){
obj.push(...item);
return obj;
},[]);
console.log(array)