Convert Object to 2D array in JavaScript - javascript

Can we convert an Object to a 2D Array,
My Object is like this
So That Array Key will be like 'STARS_2' and value is ["STARS_4", "STARS_0", "STARS_12"]
with My attempts I can get something like this,
With this Code,
var testArray =[];
_.map(childFieldNames, function (value, key) {
var newArray = new Array();
newArray[key] = value;
testArray.push(newArray);
});
Here Keys are actually another array, which I do not want. I want key should be like 'STARS_2' , i.e. property of master object.

Is this what you need?
var ary2D = Object.keys(childFieldNames).map(function (key) {
return childFieldNames[key];
});

better version for what Shilly showed would be:
const arr2D = Object.values(childFieldNames);

Object.entries(obj)
E.g.
const objVariable = {name: "Ted", job: "Dentist"}
const 2dArray = Object.entries(objVariable)
console.log(2dArray) // will print [["name", "Ted"], ["job", "Dentist"]]
Object.entries is a static method that belongs to the Object class. As a parameter, it accepts an object and returns a two-dimensional array.
Read more about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

You don’t need to create your structure into 2D array to just iterate over each key and its respective value(which is an array). If you want to iterate over it you can do something like this.
const object = {
a: [1,2,3],
b: [2,3,5]
};
for (const [key, value] of Object.entries(object)) {
value.forEach(v=>{
console.log(`${key}: ${v}`);
})
}

Related

How to merge multiple JSON objects to one single json object in javascript

My requirement is to get the json objects from different sources and merge them into one single json object using javascript
example:
Below there are 2 json objects with different values and I want to make it as one final Json object and append new value to the final result
json1= {
"b":"test1",
"a":"test3",
"type":"sample1"
}
json2= {
"endDate":"ddd1",
"startDate":"dd01"
}
Expected results should be like below
result = {
"b":"test1",
"a":"test3",
"type":"sample1",
"endDate":"ddd1",
"startDate":"dd01"
}
Can anyone suggest me the best way to achieve this in javascript please ?
You can use the rest operator to remove type property and then assign values from 1st object to new property of the merged object
let mergeObjects = (a, b) => {
let {type, ...rest} = b; //remove type property
for(let prop in rest){
if(a[prop]){
rest[prop].xyz = a[prop];
}
}
return rest;
}
let Object3= mergeObjects(Object1, Object2);
console.log(Object3);
Can be as simple as this:
let Object1 ={"b":"test1","a":"test3","type":"sample1"};let Object2 ={"b":{"endDate":"ddd1","startDate":"dd01"},"a":{"endDate":"31","startDate":"01"},"type":"sample2"}
let Object3 = Object2;
for (let i in Object3){
Object3[i]["XYZ"] = Object1[i]
}
Object3["type"] = "12345"
console.log(Object3)

transform array to dynamic object

I would like to transform the following array which is dynamic to an dynamic object
e.g.
let
array=[{"MyFirstValue":"1"},{MySecondvalue:"2"}]
I would like to convert it ti an dynamic object
like
let newobject={MyFirstValue:"1",MySecondvalue:"2" }
The dynamic object here is that depending upon the numbers of values in the array the newobject should be able to transform
e.g.
if the array value changes =
array=[{"MyFirstValue":"1"},{MySecondvalue:"2"},{MyThirdValue:"2"}]
The newobject should transform to
newobject={MyFirstValue:"1",MySecondvalue:"2",MyThirdValue:"2" }
I tried using array.map and pushing the value but could not set the key property
It is like reducing the reducing the array to an object. I am not sure if i can use reduce.
You can accomplish this using Object.assign assuming your keys are unique.
const array = [{"key1":"1"}, {"key2":"2"}];
const newObject = Object.assign({}, ...array);
console.log(newObject);
You need to have unique keys in your object. Also, you should not expect all your objects to have 100% unique keys. Instead of having {key: 1, key: 2}, why not have the property key be an array of values; {key: [1, 2]}. I would use Array.prototype.reduce to achieve this.
const array = [{"key":"1", other: 'FOO'},{key:"2", dynamic: 'BAR', other: 'BAZ'}]
const object = array.reduce((initial, value) => {
Object.keys(value).forEach((key) => {
if(initial[key]) initial[key].push(value[key])
else initial[key] = [value[key]]
})
return initial;
}, {})
console.log(object)
try
let newobject= array.reduce((x,y)=> ({...x,...y}), {});
let array=[{"MyFirstValue":"1"},{MySecondvalue:"2"}]
let newobject= array.reduce((x,y)=> ({...x,...y}), {});
console.log(newobject);
Using ES5:
var input = [{"MyFirstValue":"1"},{MySecondvalue:"2"},{MyThirdValue:"2"}];
var output = Object.assign.apply({}, input);
console.log(output);

Cannot get/fetch keys from an array in javascript

I have an array object where there are key value pairs. I am trying to get the keys in that array using a loop but I am getting only 0. What is the problem with my code.
var strj = '{"name":"John","age":"30","cars":
[ {"type":"car", "year":"1998"},
{"type":"van", "year":"1995"}]}';
var myobj = JSON.parse(strj)
var care = myobj.cars.filter(c => c.type=='car');
Value of care
0:{type: "car", year: "1998"}
length:1
__proto__:Array(0)
Loop
for (var key in care){
if(care.hasOwnProperty(key)){
console.log(key)
}
}
care is a array type so you cannot do for (var key in care). You need to do for (var key in care[0]). This is because for (var key in care) will look for the key value in care and since it is a array it will always take 0 as a value in key(as you have only one object in array and its index is 0). That is why you got 0 in console.log.
var care =[{type: "car", year: "1998"}];
for (var key in care[0]){
if(care[0].hasOwnProperty(key)){
console.log(key)
}
}
care.forEach( ( singleCar ) => {
for ( var key in singleCar ){
console.log(key);
if( care.hasOwnProperty( key ) ){
console.log(key);
}
}
})
forEach will give you all the objects one by one. so you can check them.
As others have solved the issue, might i make a suggestion - Object.keys () gives an array of the keys for a given object. Since you are getting your filtered object and simply want its keys - the following will achieve that. Note that this is only using the code after you have filtered the original and have gained the "care" object.
As an aside, note that object.values() will give you an array of the values in a given object and object.entries() will give you arrays of the key / value pairing.
var care = {type: "car", year: "1998"};
var keys = Object.keys(care)
console.log(keys) // gives ["type","year"]
filter() method returns a Array of matches.
var care = myobj.cars.filter(c => c.type=='car'); // So, this returns an array.
care.forEach(element => {
console.log(Object.keys(element)); //Prints keys of each element
});
Well actually there is no problem in your code at all. But you just misunderstood the use of javascript filter. Javascript filter() creates new array that's why you are getting 0 as key. If you want to get only one matching element then find() is what you should use.
var strj = '{"name":"John","age":"30","cars":[{"type":"car", "year":"1998"},{"type":"van", "year":"1995"}]}';
var myobj = JSON.parse(strj)
var care = myobj.cars.filter(c => c.type == 'car'); // returns array
var care = myobj.cars.find(c => c.type == 'car'); // returns first matching object
var care = myobj.cars.findIndex(c => c.type == 'car'); // returns first matching index
Javascript filter() method => Read Here
Javascript find() => Read Here
Javascript findIndex() method => Read Here

get key and value of array via underscore each

I would like to loop through an array and get the key and value of it. This is what I'm doing, but I don't get any output. What am I doing wrong?
let regexes = [];
regexes['some.thing'] = /([^.]+)[.\s]*/g;
_.each(regexes, function(regex, key) {
console.log(regex, key);
});
You are using array and adding a property to it which is not valid .Use object for it
let regexes = {};
regexes['some.thing'] = /([^.]+)[.\s]*/g;
_.each(regexes, function(regex, key) {
console.log(regex, key);
});
_.each iterates through the indices of the array. You are adding a non-numeric property to the array object. Your array is empty and _.each callback is not executed. It seems you want to use a regular object ({}) and not an array:
let regexes = {};
Now _.each should iterate through the object own (by using hasOwnProperty method) properties.
You are assigning a property to the array. Lodash is attempting to iterate through the numeric indices of the array, but there are none. Change the array to an object and Lodash will iterate through its enumerable properties:
let regexes = {};
regexes['some.thing'] = /([^.]+)[.\s]*/g;
_.forEach(regexes, function(regex, key) {
console.log(regex, key);
});
Alternatively, if using an array is necessary, simply push the value onto it:
let regexes = [];
regexes.push(/([^.]+)[.\s]*/g);
_.forEach(regexes, function(regex, i) {
console.log(regex, i);
});

Sort javascript key/value pairs inside object

I have some problem with sorting items inside object. So I have something like this:
var someObject = {
'type1': 'abc',
'type2': 'gty',
'type3': 'qwe',
'type4': 'bbvdd',
'type5': 'zxczvdf'
};
I want to sort someObject by value, and this is where I have problem.
I have sorting function that should return key/value pairs sorted by value:
function SortObject(passedObject) {
var values = [];
var sorted_obj = {};
for (var key in passedObject) {
if (passedObject.hasOwnProperty(key)) {
values.push(passedObject[key]);
}
}
// sort keys
values.sort();
// create new object based on Sorted Keys
jQuery.each(values, function (i, value) {
var key = GetKey(passedObject, value);
sorted_obj[key] = value;
});
return sorted_obj;
}
and function to get key:
function GetKey(someObject, value) {
for (var key in someObject) {
if (someObject[key] === value) {
return key;
}
}
}
The problem is in last part when creating new, returning object - it's sorted by key again. Why? And this is specific situation when i have to operate on object NOT on array (yes I know that would be easier...)
Does anyone know how to sort items in object?
Plain objects don't have order at all. Arrays -that are a special types of objects- have.
The most close thing that you can have is an array with the object values sorted . Something like, for example:
_valuesOfAnObjectSorted = Object.keys(object).map(function(k){ return object[k]; }).sort();
You have two possibilities:
Refactor your object into an array
Something like this:
var myObj = [
['type1', 'abc'],
['type2', 'gty'],
...
];
Or even better, since using it somewhere would not rely on array positions but full named keys:
var myObj = [
{name: 'type1', val:'abc'},
{name: 'type2', val:'gty'},
...
];
Use your object with an auxiliar array
Wherever you want to use your object ordered by the keys, you can extract the keys as an array, order it and traverse it to access the object
var ordKeys = Object.keys(myObj).sort(); // pass inside a function if you want specific order
var key;
for (var i = 0, len = ordKeys.length; i < len; i +=1) {
key = ordKeys[i]
alert(key + " - " + myObj[key]);
}
Combination of both of them
If the object is not constructed by you, but comes from somewhere else, you can use the second option approach to construct an array of objects as in the first option. That would let you use your array anywhere with perfect order.
EDIT
You might want to check the library underscore.js. There you have extremely useful methods that could do the trick pretty easily. Probably the method _.pairs with some mapping would do all the work in one statement.

Categories

Resources