Convert object into 2-d array but remove keys - javascript

I am trying to convert the below this:
let JSON = [
{1:"hello",2:"goodbye",3:"bonjour"},
{4:"hello2",5:"goodbye2",6:"bonjour2"},
{7:"hello3",8:"goodbye3",9:"bonjour3"},
{10:"hello4",11:"goodbye4",12:"bonjour4"}
]
to this:
let arr = [
["hello","goodbye","bonjour"],
["hello2","goodbye2","bonjour2"],
["hello3","goodbye3","bonjour3"],
["hello4","goodbye4","bonjour4"]
]
I have tried:
var row1 = JSON.map(function(e) {
return [ e.1, e.2, e.3];
});
var row2 = JSON.map(function(e) {
return [ e.4, e.5, e.6];
});
var row3 = JSON.map(function(e) {
return [ e.7, e.8, e.9];
});
var row4 = JSON.map(function(e) {
return [ e.10, e.11, e.12];
let array = [row1,row2,row3,row4]
But cannot get anything working. I would appreciate any help :)

Try this one:
let JSON = [
{1:"hello",2:"goodbye",3:"bonjour"},
{4:"hello2",5:"goodbye2",6:"bonjour2"},
{7:"hello3",8:"goodbye3",9:"bonjour3"},
{10:"hello4",11:"goodbye4",12:"bonjour4"}
];
let arr = JSON.map(obj => {
return Object.values(obj);
});

You can use a standard for loop to iterate the object key's and push the object values into an array(ordered) which you return, all within the callback of Array.map. Also, your problem is that Array.map works on every item of the array, not just one at a time. that is why your code doesn't work the way you expected.
let JSON = [
{1:"hello",2:"goodbye",3:"bonjour"},
{4:"hello2",5:"goodbye2",6:"bonjour2"},
{7:"hello3",8:"goodbye3",9:"bonjour3"},
{10:"hello4",11:"goodbye4",12:"bonjour4"}
]
const result = JSON.map(a=>{
const b = [];
for(var k in a){
b.push(a[k]);
}
return b;
});
console.log(result);

Given your sample data, it seems you could simply use Object.values:
let original = [
{1:"hello",2:"goodbye",3:"bonjour"},
{4:"hello2",5:"goodbye2",6:"bonjour2"},
{7:"hello3",8:"goodbye3",9:"bonjour3"},
{10:"hello4",11:"goodbye4",12:"bonjour4"}
]
var array = original.map(Object.values);
console.log(array);
This works because the order of elements in each object is the same as the order you want to achieve in the result array.
If you this is not always the case (e.g. you have {12:"bonjour4",11:"goodbye4",10:"hello4"} and you still want to return ["hello4","goodbye4","bonjour4"]) you can sort entries by their keys first. For example:
let original = [
{1:"hello",2:"goodbye",3:"bonjour"},
{4:"hello2",5:"goodbye2",6:"bonjour2"},
{7:"hello3",8:"goodbye3",9:"bonjour3"},
{12:"bonjour4",11:"goodbye4",10:"hello4"}
]
var array = original
.map(obj => Object
.entries(obj)
.sort(([k1], [k2]) => k1 - k2)
.map(([_, v]) => v));
console.log(array);
As a side note, I'd caution you against using the name JSON since this will hide the built-in JSON object.

Related

Create new array with Average of same keys in an array of objects

I have an array of object as follows:
var arr=[ {"jan":2},{"jan":5},{"feb":3},{"feb":1}];
Their will be N number of objects with any combination keys jan & feb is just an example.
I need to find average of objects with similar keys so that resultant array looks like this :
var newArr=[{"jan":3.5},{"feb":2}];
Looking to achieve this without reduce method in JavaScript.
I tried to seperate out objects with similar keys so that ic an sum and average them and push in to a new aray. something like this :
arr.forEach(a=>{
console.log(Object.keys(a))
console.log(arr.filter(ar=>ar.hasOwnProperty(Object.keys(a)[0])))
})
But it creates multiple groups for same keys like this in console.
[ {"jan":2},{"jan":5} ]
[ {"jan":2},{"jan":5} ]
[ {"feb":3},{"feb":1} ]
[ {"feb":3},{"feb":1} ]
A code without using reduce . A bit length though but easy to understand
We are using two objects , one is to store the count of the keys and other is for storing the total of the keys.
result object has the average.
var arr=[ {"jan":2},{"jan":5},{"feb":3},{"feb":1}];
var count = {};
var total = {};
arr.forEach(obj => {
var key = Object.keys(obj)[0];
if(count.hasOwnProperty(key)){
count[key]=count[key]+1;
} else {
count[key]=1;
}
if(total.hasOwnProperty(key)){
total[key]=total[key]+obj[key];
} else {
total[key]=obj[key];
}
})
var result = {}
Object.keys(total).forEach(key => {
result[key] = total[key]/count[key];
})
console.log(result)
Similar to the answer above, but makes use of a map:
var arr=[ {"jan":2},{"jan":5},{"feb":3},{"feb":1}];
let map = new Map();
let keyCount = {};
arr.forEach(e => {
let key = Object.keys(e)[0];
let value = Object.values(e)[0];
if (map.get(key) !== undefined) {
map.set(key, map.get(key) + value);
keyCount[key] = keyCount[key] + 1;
} else {
map.set(key, value);
keyCount[key] = 1;
}
});
let newArr = [];
for (let e of map.entries()) {
let obj = {};
obj[e[0]] = e[1] / keyCount[e[0]];
newArr.push(obj);
}
console.log(newArr);

json object to array of strings

I have the following JSON:
{
"tagExpression": "#debug",
"project": "Project_PERSONAL"
}
And I need to convert it to the following array of strings:
[ "tagExpression:#debug",
"project: Project_PERSONAL" ]
This is the code I wrote, and i would like to know maybe is a better way to do it, the code read the JSON from a file, then performs a for loop to convert it:
logger.info(`Updating run configuration base on process args`);
let path = String(processArgvHelper.getArgValue("overrideConf"));
let fileconf = JSON.parse(require("fs").readFileSync(path));
let fileConfStr = String(Object.entries(fileconf)).split(",");
let fileConfArr = [];
for(let i=0;i<fileConfStr.length;i++){
logger.info(`${fileConfStr[i]} -- ${i}`);
if(i === 0 || (i%2)==0){
fileConfArr.push(`${fileConfStr[i]}:${fileConfStr[i+1]}`);
logger.info(`${fileConfStr[i]}:${fileConfStr[i+1]}`)
}
}
Then fileConfArr contains the desired converted array of strings.
You can iterate over the object keys and then map it together
var myObject = {
"tagExpression": "#debug",
"project": "Project_PERSONAL"
}
var result = Object.keys(myObject).map(function(key) {
return key + ':' + myObject[key];
});
console.log(result);
Object.entries(obj).map(([k,v])=> `${k}:${v}`)
Use a for in loop to iterate over an object and then push key and the corresponding value to the resultant array
var input = {
tagExpression: "#debug",
project: "Project_PERSONAL"
};
var out = [];
for (var key in input) {
out.push(`${key}: ${input[key]}`);
}
console.log(out);
Here is my solution for this solution.
const jsonData = `{
"tagExpression": "#debug",
"project": "Project_PERSONAL"
}`;
const obj = JSON.parse(jsonData);
const result = Object.keys(obj).reduce((arr, key) => {
let str = `${key}: ${obj[key]}`;
arr.push(str);
return arr;
}, []);
console.log(result);
First, you extract the keys into an array
Then map each key and return a key and value
Here is the code snippet
let fileconf = {
"tagExpression": "#debug",
"project": "Project_PERSONAL"
}
let arrOfkeys = Object.keys(fileconf);
let fileConfArr = arrOfkeys.map(key => key + fileconf[key]);
fileconf[key] returns the value of that key
I don't know if it's better, or how to define "better" for this, but i would do it like this:
let stringifiedJson = JSON.stringify(fileConf);
let stringWithoutBrackets = stringifiedJson.substring(1, stringifiedJson.length - 1);
let finalArray = stringWithoutBrackets.split(',').map(it => it.replace(/\"/g, ""));

How to use split on a string and then convert it to object in Javascript

I have an array:
let arr = ["a=1", "b=22", "c=11"];
And I want to split the string inside array so it becomes an object later, which will look like:
{a: 1, b: 22, c: 11}
Can I somehow do that
You could split the string an map new objects. Later assign all objects to a single object.
var array = ["a=1", "b=22", "c=11"],
object = Object.assign(
...array.map(s => ((k, v) => ({ [k]: +v }))(...s.split('=')))
);
console.log(object);
you can use array.forEach, so you wont be creating an array instead you will iterate through the array, and you can take each item and split so it will create an array
like item = ["a", "1"], you can assign the key as a to the object which is the first index and value is second index,The value is string so you can convert to number and return it.
let arr = ["a=1", "b=22", "c=11"];
var obj = {}
arr.forEach(o => {
var item = o.split("=");
return obj[item[0]] = Number(item[1])
})
console.log("required obj", obj)
You can use array#map with Object.assign() to create your object. string#split each word on = and generate the object.
let arr = ["a=1", "b=22", "c=11"],
result = Object.assign(...arr.map(word => {
let [key,value] = word.split('=');
return {[key] : +value};
}));
console.log(result);
You can also use array#reduce.
let arr = ["a=1", "b=22", "c=11"],
result = arr.reduce((r,word) => {
let [key,value] = word.split('=');
r[key] = +value;
return r;
}, {});
console.log(result);
Here, try this
let arr = ["a=1", "b=22", "c=11"];
const obj = {}
arr.forEach(i => {
const splitted = i.split('=')
obj[splitted[0]] = splitted[1]
} )
console.log(obj)

Javascript merge two array

I have two array.They looks like
var productId = [2,3,5];
var quantity = [10,13,15];
Now I want to merge these array in one array and store in local storage.New array looks like
var newArray = [2 =>'10',3=>'13',5=>'15'];
You can create object instead using Object.assign and map methods.
var productId = [2,3,5];
var quantity = [10,13,15];
var obj = Object.assign({}, ...productId.map((e, i) => ({[e]: quantity[i]})))
console.log(obj)
// localStorage.setItem('foo', JSON.stringify(obj))
// console.log(JSON.parse(localStorage.getItem('foo')))
Or you can use reduce method instead of map.
var productId = [2,3,5];
var quantity = [10,13,15];
var obj = productId.reduce((r, e, i) => (r[e]= quantity[i], r), {})
console.log(obj)
I can see that you want to merge two arrays with same length such that merged array will have keys from first array and values from second array. But unlike php, JavaScript doesn’t have concept of array with key and value pairs. What you can do is create a merged object with key value pair.You can achieve by creating a custom function which does that. So, the code for it would be something like:
let arrayA = ["name", "address", "phone"];
let arrayB = ["Niraj", "Kathmandu", "98423232223"];
function array_combine(a, b)
{
if(a.length != b.length) return false;
let combObj = {};
for (i = 0; i < a.length; i++)
{
combObj[a[i]] = b[i];
}
return combObj;
}
let combined_obj = array_combine(arrayA, arrayB);
console.log(combined_obj);
You can directly use reduce method of ES6 as well for the purpose.
let arrayA = ["name", "address", "phone"];
let arrayB = ["Niraj", "Kathmandu", "98423232223"];
let combined_obj =
arrayA.reduce((obj, k, i) => ({...obj, [k]: arrayB[i] }), {}));
If you now want to store the combined_array in local storage, you can do that, by first stringifying it and then store it.
let combined_obj = JSON.stringify(array_combine(arrayA, arrayB));
localStorage.setItem('combinedObj', combined_obj);

Checking multiple variables with the same "rules"

I have to construct an array of objects. I can do it "long hand," but I'm hoping to find a way to iterate through some variables and check each at "push" them into the right spot in the array.
I have this:
//this is the starting array...I'm going to update these objects
operationTime = [
{"isActive":false,"timeFrom":null,"timeTill":null},//Monday which is operationTime[0]
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null}
];
//I get the below via an API call
var monHours = placeHours.mon_open_close;
var tueHours = placeHours.tue_open_close;
var wedHours = placeHours.wed_open_close;
var thuHours = placeHours.thu_open_close;
var friHours = placeHours.fri_open_close;
var satHours = placeHours.sat_open_close;
var sunHours = placeHours.sun_open_close;
var sunHours = placeHours.sun_open_close;
//here's where I'm stuck.
if (monHours.length>0){
var arr = monHours[0].split("-");
operationTime[0].isActive= true;
operationTime[0].timeFrom= arr[0];
operationTime[0].timeTill= arr[1];
}
else {
operationTime[0].isActive= false;
}
My if/else works perfectly in the above example using Monday, but I don't want to write this for seven days of the week making it unnecessarily complicated. How could I condense this into a single "function" that'll test each variable and push it into the array object in the correct position?
I guess you can put the keys in an array, and then use forEach loop through operationTime and update the object based on the index:
operationTime = [
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null}
];
// make an array of keys that has the same order of the operationTime
var keys = ['mon_open_close', 'tue_open_close', 'wed_open_close', 'thu_open_close', 'fri_open_close', 'sat_open_close', 'sun_open_close'];
var placeHours = {'mon_open_close': ['08:00-17:00'], 'tue_open_close':[], 'wed_open_close':[], 'thu_open_close':[], 'fri_open_close':[], 'sat_open_close':[], 'sun_open_close':['10:20-15:30']}
operationTime.forEach( (obj, index) => {
var dayHours = placeHours[keys[index]];
if(dayHours.length > 0) {
var arr = dayHours[0].split("-");
obj.isActive= true;
obj.timeFrom= arr[0];
obj.timeTill= arr[1];
}
})
console.log(operationTime);
You can try this way with foreach all days's hour,
$all_hours = [monHours, tueHours , wedHours , thuHours , friHours , satHours ,sunHours];
foreach($all_hours as $k=>$hours){
if ($hours.length>0){
$arr = $hours[k].split("-");
operationTime[$k].isActive= true;
operationTime[$k].timeFrom= $arr[0];
operationTime[$k].timeTill= $arr[1];
}
else {
operationTime[$k].isActive = false;
}
}
You can use Object.entries() to iterate properties and values of an object as an array, .map() to define and include index of iteration in block of for..of or other loop. The index is utilized to reference object at index of operationTime array
for (let
[key, prop, index]
of
Object.entries(placeHours)
.map(([key, prop], index) => [key, prop, index]))) {
if (prop.length > 0 ) {
let [arr] = prop.split("-");
operationTime[index].isActive = true;
operationTime[index].timeFrom = arr[0];
operationTime[index].timeTill = arr[1];
}
}

Categories

Resources