Issue with parsing the data into an integer JSON Array - javascript

I have a json file
{
"Val1":120,
"Val2":60,
"Val3":50
}
I need to pass those into two Global Arrays.
1st Array = ["Val1","Val2","Val3"]
2nd Array = [120,60,50]

You can use Object.keys & Object.values. Both of them will return array. Object.keys return array of keys and Object.values creates an array of values
let obj = {
"Val1": 120,
"Val2": 60,
"Val3": 50
}
let array1 = Object.keys(obj);
let array2 = Object.values(obj);
console.log(array1, array2)

You could use a for loop like the one here:
var jsonObject = {
"Val1":120,
"Val2":60,
"Val3":50
};
var arr1 = [];
var arr2 = [];
for(key in jsonObject) {
arr1.push(key);
arr2.push(jsonObject[key]);
}
console.log('Keys: ', arr1);
console.log('Values: ', arr2);

Related

How to add an array of Keys to Nested Arrays of Values [duplicate]

I have two arrays: newParamArr and paramVal.
Example values in the newParamArr array: [ "Name", "Age", "Email" ].
Example values in the paramVal array: [ "Jon", 15, "jon#gmail.com" ].
I need to create a JavaScript object that places all of the items in the array in the same object. For example { [newParamArr[0]]: paramVal[0], [newParamArr[1]]: paramVal[1], ... }.
In this case, the result should be { Name: "Jon", "Age": 15, "Email": "jon#gmail.com" }.
The lengths of the two arrays are always the same, but the length of arrays can increase or decrease. That means newParamArr.length === paramVal.length will always hold.
None of the below posts could help to answer my question:
Javascript Recursion for creating a JSON object
Recursively looping through an object to build a property list
var keys = ['foo', 'bar', 'baz'];
var values = [11, 22, 33]
var result = {};
keys.forEach((key, i) => result[key] = values[i]);
console.log(result);
Alternatively, you can use Object.assign
result = Object.assign(...keys.map((k, i) => ({[k]: values[i]})))
or the object spread syntax (ES2018):
result = keys.reduce((o, k, i) => ({...o, [k]: values[i]}), {})
or Object.fromEntries (ES2019):
Object.fromEntries(keys.map((_, i) => [keys[i], values[i]]))
In case you're using lodash, there's _.zipObject exactly for this type of thing.
Using ECMAScript2015:
const obj = newParamArr.reduce((obj, value, index) => {
obj[value] = paramArr[index];
return obj;
}, {});
(EDIT) Previously misunderstood the OP to want an array:
const arr = newParamArr.map((value, index) => ({[value]: paramArr[index]}))
I needed this in a few places so I made this function...
function zip(arr1,arr2,out={}){
arr1.map( (val,idx)=>{ out[val] = arr2[idx]; } );
return out;
}
console.log( zip( ["a","b","c"], [1,2,3] ) );
> {'a': 1, 'b': 2, 'c': 3}
I know that the question is already a year old, but here is a one-line solution:
Object.assign( ...newParamArr.map( (v, i) => ( {[v]: paramVal[i]} ) ) );
The following worked for me.
//test arrays
var newParamArr = [1, 2, 3, 4, 5];
var paramVal = ["one", "two", "three", "four", "five"];
//create an empty object to ensure it's the right type.
var obj = {};
//loop through the arrays using the first one's length since they're the same length
for(var i = 0; i < newParamArr.length; i++)
{
//set the keys and values
//avoid dot notation for the key in this case
//use square brackets to set the key to the value of the array element
obj[newParamArr[i]] = paramVal[i];
}
console.log(obj);
You can use Object.assign.apply() to merge an array of {key:value} pairs into the object you want to create:
Object.assign.apply({}, keys.map( (v, i) => ( {[v]: values[i]} ) ) )
A runnable snippet:
var keys = ['foo', 'bar', 'baz'];
var values = [11, 22, 33]
var result = Object.assign.apply({}, keys.map( (v, i) => ( {[v]: values[i]} ) ) );
console.log(result); //returns {"foo": 11, "bar": 22, "baz": 33}
See the documentation for more
Object.fromEntries takes an array of key, value tuples and return the zipped result as object, you can then use it as follow:
const keys = ["a","b","c"];
const values = [1,2,3];
Object.fromEntries(keys.map((key, index)=> [key, values[index]])); // {a: 1, b: 2, c: 3}
Use a loop:
var result = {};
for (var i = 0; i < newParamArr.length; i++) {
result[newParamArr[i]] = paramArr[i];
}
This one works for me.
var keys = ['foo', 'bar', 'baz'];
var values = [11, 22, 33]
var result = {};
keys.forEach(function(key, i){result[key] = values[i]});
console.log(result);

How to convert an array of strings into an array of objects with non index keys and dynamic values in JavaScript [duplicate]

I have two arrays: newParamArr and paramVal.
Example values in the newParamArr array: [ "Name", "Age", "Email" ].
Example values in the paramVal array: [ "Jon", 15, "jon#gmail.com" ].
I need to create a JavaScript object that places all of the items in the array in the same object. For example { [newParamArr[0]]: paramVal[0], [newParamArr[1]]: paramVal[1], ... }.
In this case, the result should be { Name: "Jon", "Age": 15, "Email": "jon#gmail.com" }.
The lengths of the two arrays are always the same, but the length of arrays can increase or decrease. That means newParamArr.length === paramVal.length will always hold.
None of the below posts could help to answer my question:
Javascript Recursion for creating a JSON object
Recursively looping through an object to build a property list
var keys = ['foo', 'bar', 'baz'];
var values = [11, 22, 33]
var result = {};
keys.forEach((key, i) => result[key] = values[i]);
console.log(result);
Alternatively, you can use Object.assign
result = Object.assign(...keys.map((k, i) => ({[k]: values[i]})))
or the object spread syntax (ES2018):
result = keys.reduce((o, k, i) => ({...o, [k]: values[i]}), {})
or Object.fromEntries (ES2019):
Object.fromEntries(keys.map((_, i) => [keys[i], values[i]]))
In case you're using lodash, there's _.zipObject exactly for this type of thing.
Using ECMAScript2015:
const obj = newParamArr.reduce((obj, value, index) => {
obj[value] = paramArr[index];
return obj;
}, {});
(EDIT) Previously misunderstood the OP to want an array:
const arr = newParamArr.map((value, index) => ({[value]: paramArr[index]}))
I needed this in a few places so I made this function...
function zip(arr1,arr2,out={}){
arr1.map( (val,idx)=>{ out[val] = arr2[idx]; } );
return out;
}
console.log( zip( ["a","b","c"], [1,2,3] ) );
> {'a': 1, 'b': 2, 'c': 3}
I know that the question is already a year old, but here is a one-line solution:
Object.assign( ...newParamArr.map( (v, i) => ( {[v]: paramVal[i]} ) ) );
The following worked for me.
//test arrays
var newParamArr = [1, 2, 3, 4, 5];
var paramVal = ["one", "two", "three", "four", "five"];
//create an empty object to ensure it's the right type.
var obj = {};
//loop through the arrays using the first one's length since they're the same length
for(var i = 0; i < newParamArr.length; i++)
{
//set the keys and values
//avoid dot notation for the key in this case
//use square brackets to set the key to the value of the array element
obj[newParamArr[i]] = paramVal[i];
}
console.log(obj);
You can use Object.assign.apply() to merge an array of {key:value} pairs into the object you want to create:
Object.assign.apply({}, keys.map( (v, i) => ( {[v]: values[i]} ) ) )
A runnable snippet:
var keys = ['foo', 'bar', 'baz'];
var values = [11, 22, 33]
var result = Object.assign.apply({}, keys.map( (v, i) => ( {[v]: values[i]} ) ) );
console.log(result); //returns {"foo": 11, "bar": 22, "baz": 33}
See the documentation for more
Object.fromEntries takes an array of key, value tuples and return the zipped result as object, you can then use it as follow:
const keys = ["a","b","c"];
const values = [1,2,3];
Object.fromEntries(keys.map((key, index)=> [key, values[index]])); // {a: 1, b: 2, c: 3}
Use a loop:
var result = {};
for (var i = 0; i < newParamArr.length; i++) {
result[newParamArr[i]] = paramArr[i];
}
This one works for me.
var keys = ['foo', 'bar', 'baz'];
var values = [11, 22, 33]
var result = {};
keys.forEach(function(key, i){result[key] = values[i]});
console.log(result);

Find elements in an array not contained in another array of objects

I have an array arr1 = [1,2,3,4,5]
There is another array of objects arr2 = [{'id':2, 'name':'A'},{'id':4, 'name':'B'}]
I am looking for find elements in arr1 which are not in arr2. The expected output is [1,3,5]
I tried the following but it doesn't work.
const arr = arr1.filter(i => arr2.includes(i.id));
Can you please help?
A solution with O(arr2.length) + O(arr1.length) complexity in Vanilla JS
var arr1= [1,2,3,4,5];
var arr2 = [{'id':2, 'name':'A'},{'id':4, 'name':'B'}];
var tmp = arr2.reduce(function (acc, obj) {
acc[obj['id']] = true;
return acc;
}, {});
var result = arr1.filter(function(nr) {
return !tmp.hasOwnProperty(nr);
})
arr2 is an array of objects, so arr2.includes(i.id) doesn't work because i (an item from arr1) is a number, which doesn't have an id property, and because arr2 is an array of objects.
Turn arr2's ids into a Set first, then check whether the set contains the item being iterated over:
const arr1 = [1,2,3,4,5];
const arr2 = [{'id':2, 'name':'A'},{'id':4, 'name':'B'}];
const ids = new Set(arr2.map(({ id }) => id));
const filtered = arr1.filter(num => !ids.has(num));
console.log(filtered);
You can try with Array.prototype.some():
The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.
const arr1 = [1,2,3,4,5]
const arr2 = [{'id':2, 'name':'A'},{'id':4, 'name':'B'}]
const arr = arr1.filter(i => !arr2.some(j => j.id == i));
console.log(arr);
We can use the filter method like below to check the condition required
var arr1 = [1, 2, 3, 4, 5]
var arr2 = [{ 'id': 2, 'name': 'A' }, { 'id': 4, 'name': 'B' }]
var ids = [];
arr2.forEach(element => {
ids.push(element['id'])
});
var result = arr1.filter(s => ids.indexOf(s) < 0)
console.log(result)
let arr1= [1,2,3,4,5];
let arr2 = [{'id':2, 'name':'A'},{'id':4, 'name':'B'}]
let arr2Ids=arr2.map(item=>item.id);
let result=arr1.filter(n => !arr2Ids.includes(n));
You can use find on arr2 instead of includes since arr2 is composed of object
const arr = arr1.filter(i => !arr2.find(e => e.id===i));

How to make two arrays from this json data?

My data is animalCount: {Tiger: 3, Leopard: 6, Rat: 1}
So I need to have 1st array
name :['Tiger', 'Leopard', 'Rat']
2nd array
count: [3, 6, 1]
Is it possible to obtain the same?
Sure, just use:
const names = Object.keys(animalCount);
const values = Object.values(animalCount);
As others have mentioned, you can use:
var name = Object.keys(animalCount);
var count = Object.values(animalCount);
If you, for some reason, needed to manipulate or change them while creating these arrays, you could also use a for i in animalCount loop, like so:
var animalCount = {Tiger: 3, Leopard: 6, Rat: 1};
var array1 = [];
var array2 = [];
for(i in animalCount){
if(animalCount.hasOwnProperty(i)){
array1.push(i);
array2.push(animalCount[i]);
}
}
console.log(array1);
console.log(array2);
How about
var name = [];
var count = [];
for(var prop in animalCount){
name.push(prop);
count.push(animalCount[prop]);
}
This way we're sure the order is preserved.
JS supports this natively.
var name = Object.keys(animalCount);
var count = Object.values(animalCount);
See:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys for Object.keys and
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values for Object.values
You could take a single loop and reduce the entries of the object by iterating the key/value array for pushing the items.
var animalCount = { Tiger: 3, Leopard: 6, Rat: 1 },
names = [],
count = [],
result = Object
.entries(animalCount)
.reduce((r, a) => (a.forEach((v, i) => r[i].push(v)), r), [names, count]);
console.log(names);
console.log(count);
.as-console-wrapper { max-height: 100% !important; top: 0; }

How do you merge the item values from 2 separate arrays in javascript?

I'm not looking to push the values from one array into another, or concatenate them but simply sum the item values from each - either into a new array, or alternatively amending either arrayOne or arrayTwo with the values from the other e.g.
var arrayOne = [1,2,3,4,5]
var arrayTwo = [2,4,6,8,10]
// loop / function..
var newArray = [3,6,9,12,15]
OR arrayOne = [3,6,9,12,15]
I thought this would be straightforward but this requires 2 loops running at the same time?
Thanks for your help!
var arrayOne = [1,2,3,4,5];
var arrayTwo = [2,4,6,8,10];
var newArray = [];
newArray = arr1.map((item,index)=>{
return item + arr2[index]
});
You could collect all wanted array for adding values at the same index in an array and reduce the arrays.
This works with an arbitrary count of arrays.
var array1 = [1, 2, 3, 4, 5],
array2 = [2, 4, 6, 8, 10],
result = [array1, array2].reduce(
(a, b) => (b.forEach((v, i) => a[i] = (a[i] || 0) + v), a)
);
console.log(result);
You can use Array's map():
var arrayOne = [1,2,3,4,5];
var arrayTwo = [2,4,6,8,10];
var newArray = arrayOne.map( (item, i) => item += arrayTwo[i] );
console.log(newArray);

Categories

Resources