I have seen lots of answers in the other way,
but i couldnt find array of objects into object of objects
the following example of what I want:
i want to transform this:
var = [
{"a" : {"min" : 0.5}},
{"b" : {"max" : 0.6}},
{"c" : {"min" : 0.3}}]
to this:
var = {
"a" : {"min" : 0.5},
"b" : {"max" : 0.6},
"c" : {"min" : 0.3}
}
array of objets to object of objects,
So I can use this solver: https://github.com/JWally/jsLPSolver
thanks
You can do this using Object.assign() and ES6 spread syntax.
var arr = [{"a" : {"min" : 0.5}}, {"b" : {"max" : 0.6}}, {"c" : {"min" : 0.3}}]
var result = Object.assign({}, ...arr);
console.log(result)
const obj = arr.reduce((result, item) => {
const key = Object.keys(item)[0];
result[key] = item[key];
return result;
}, {});
Array.prototype.reduce() and Object.keys() are your friends in here.
I think it is kind of difficult to generalize this and make it more generic, since you have to know which key of the item should be used as key of the result. But in this case, there is only one, so easy to use.
I suppose you should create class or struct of objects.
You can do like this. First loop over the array and just add the key & value from each object to the new object
var firstArray = [{
"a": {
"min": 0.5
}
},
{
"b": {
"max": 0.6
}
},
{
"c": {
"min": 0.3
}
}
]
var arrayKey = {};
firstArray.forEach(function(item) {
for (var keys in item) {
arrayKey[keys] = item[keys]
}
})
console.log(arrayKey)
Related
I have an array. The data in the array is in the following format.
var test = [
{
"a" : {
"order" : 100,
}
},
{
"b" : {
"order" : 10,
}
},
{
"c" : {
"order" : 1,
}
},
];
I want to sort this data according to order value. Is there any way to do this?
You can use Object.values to get the first property value and access the order property on that to compare.
let test=[{a:{order:100}},{b:{order:10}},{c:{order:1}}];
test.sort((a, b)=>Object.values(a)[0].order - Object.values(b)[0].order);
console.log(test);
For a more generalized solution, you can create a key extractor function to get the value to compare by.
let test=[{a:{order:100}},{b:{order:10}},{c:{order:1}}];
const getOrder = x => Object.values(x)[0].order;
test.sort((a, b)=>getOrder(a) - getOrder(b));
console.log(test);
You can use JS custom sort from Array.prototype.sort(), reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
Then you can sort by comparing the two element's order, but you still need to determine it's key/attribute (e.g.: a or b or c)
Here, you can use Object.keys() function and take the first key in the object, reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
Here's a working example:
var test = [
{
"a" : {
"order" : 100,
}
},
{
"b" : {
"order" : 10,
}
},
{
"c" : {
"order" : 1,
}
},
];
//console.log(test);
test.sort((firstEl, secondEl) => {
var key1 = Object.keys(firstEl)[0];
var key2 = Object.keys(secondEl)[0];
return firstEl[key1].order - secondEl[key2].order
} );
console.log(test);
Output:
[
{
"c": {
"order": 1
}
},
{
"b": {
"order": 10
}
},
{
"a": {
"order": 100
}
}
]
I have an object and an array of following kind
var sourceObject = { "item1" : 15 , "item2" : 20 " }
var feature = ["field1", "field2" ]
I am trying to convert the above object into an array of objects.
Number of items in the object as well as the array will be same
Resultant array of objects should like this:
var result = [ { "name" : "field1" , "value" : 15 } , { "name" : "field2" , "value": 20 }]
The ultimate goal is to read it from the sourceObject to get the each value and then pick each value from the "feature" array toform an object
Approach I have tried so far:
let result = [];
for (let value of Object.values(sourceObject)) {
let row = { "field" : "XYZ" , "value": value };
tableData.push(row);
}
Loop over the keys of sourceObject and then use Array.map()
var sourceObject = {
"item1": 15,
"item2": 20
}
var feature = ["field1", "field2"]
var result = Object.keys(sourceObject).map((key, index) => {
return {
name: feature[index],
value: sourceObject[key]
}
});
console.log(result);
Your object doesn't always guarantee order, so using .values(), .keys() etc... won't necessarily always guarantee your result. Instead, you can get the number from your fieldN string using a regular expression. Here N represents the itemN you want to retrieve from your object. Using this, you can .map() each fieldN to an object from your sourceObject.
See example below:
const sourceObject = { "item1" : 15 , "item2" : 20 };
const feature = ["field1", "field2" ];
const res = feature.map((name, i) => {
const [n] = name.match(/\d+$/g);
const value = sourceObject[`item${n}`];
return {name, value};
});
console.log(res);
I have a JSON object array where I need to rename the keys based on values in the first object. Trying to do this in NodeJS but not having any luck.
I could probably brute force it with a couple of loops but was hoping for a more scalable solution since the number of "columns" change from time to time.
Here is an example
[{"A" : "Key1", "B" : "Key2", "C" : "Key3"},
{"A" : "Data1", "B" : "Data2", "C" : "Data3"},
{"A" : "Data5", "B" : "Data5", "C" : "Data7"}]
I would like the result to be like
[{"Key1" : "Key1", "Key1" : "Key2", "Key1" : "Key3"},
{"Key1" : "Data1", "Key2" : "Data2", "Key3" : "Data3"},
{"Key1" : "Data5", "Key2" : "Data5", "Key3" : "Data7"}]
let arr = [{"A" : "Key1", "B" : "Key2", "C" : "Key3"},
{"A" : "Data1", "B" : "Data2", "C" : "Data3"},
{"A" : "Data5", "B" : "Data5", "C" : "Data7"}];
const keys = Object.keys(arr[0]).map(i => arr[0][i]);
let result = arr.map(obj => {
const replacedObj = {};
const oriKeys = Object.keys(obj);
for (let i = 0; i < keys.length; i++) {
replacedObj[keys[i]] = obj[oriKeys[i]]
};
return replacedObj;
});
console.log(JSON.stringify(result));
Using Object.entries() with some creative mapping, reducing, destructuring and spreading:
o = i.map(x => Object.entries(x).reduce((a, [k, v]) => ({...a, [i[0][k]]: v}), {}));
Complete snippet:
let input, output;
input = [
{"A" : "Key1", "B" : "Key2", "C" : "Key3"},
{"A" : "Data1", "B" : "Data2", "C" : "Data3"},
{"A" : "Data5", "B" : "Data5", "C" : "Data7"}
];
output = input.map(x => Object.entries(x).reduce((a, [k, v]) => ({...a, [input[0][k]]: v}), {}));
console.log(output);
Lets say the old array is stored in a var called oldArray:
var keys = Object.keys(oldArray[0]); // get first object keys
var newArray = oldArray.map(function(obj,index){
// Iterate over each object to replace keys
if(index === 0) return obj; /* if first object we dont need to replace
keys */
var objKeys = Object.keys(obj); //old keys for reference only
return Object assign({},{
[keys[0]]: obj[objKeys[0], // assigning first object keys with
current
[keys[1]]: obj[objKeys[1], // object values
[keys[2]]: obj[objKeys[3],
});
});
console.log(newArray);
/* You also can change the key value asignation with a for, so you
can handle not only 3 key values object, this could be optimized
with es6 ans spread operator definition but rather to implement it in
es5 for less complexity */
I have an array with few values. I want to iterate over array and add those values to an object as value starting from second object element which has null value. I cannot figure out how can I do it properly. Here is my code
let objectParameters = {
"current_lang" : currentLang,
"project_name" : null,
"project_type" : null,
"min_price" : null,
"max_price" : null
}
let arrayValues = ["Project name", "Project Type", 150, 950];
arrayValues .forEach(function(item) {
//Add array value to an object
}
Desired output
let objectParameters = {
"current_lang" : currentLang,
"project_name" : "Project name",
"project_type" : "Project Type",
"min_price" : 150,
"max_price" : 950
}
Came up with this :
let objectParameters = {
"current_lang" : "currentLang",
"project_name" : null,
"project_type" : null,
"min_price" : null,
"max_price" : null
};
let arrayValues = ["Project name", "Project Type", 150, 950],
keys = Object.keys(objectParameters);
keys.shift() // Removing the first key, which is not null
keys.forEach( (key,i) => objectParameters[key] = arrayValues[i])
console.log(objectParameters)
You can get all the properties of an object with
Object.keys(objectParameters)
as an array and assign them values from your arrayValues
Like that:
let objectParameters = {
"current_lang" : "en",
"project_name" : null,
"project_type" : null,
"min_price" : null,
"max_price" : null
}
let arrayValues = ["Project name", "Project Type", 150, 950];
let params = Object.keys(objectParameters);
for(let i = 1; i < params.length; i++) {
objectParameters[params[i]] = arrayValues[i-1];
}
console.log(objectParameters);
Using for in loop to iterate through the object and shift() to get the first array element each iteration, in all cases we rely on the order, that is probably not a good approach.
let objectParameters = {
"current_lang" : "currentLang",
"project_name" : null,
"project_type" : null,
"min_price" : null,
"max_price" : null
}
let arrayValues = ["Project name", "Project Type", 150, 950];
for(let p in objectParameters){
if(!objectParameters[p])
objectParameters[p] = arrayValues.shift()
}
console.log(objectParameters)
I don't see necessary to use hasOwnProperty in this case.
If you know the index of the corresponding value in the array you dont need the loop and can just do:
objectParameters["project_name"] = arrayValues[0]
objectParameters["project_type"] = arrayValues[1]
...
if you have the array values when youre creating the object you can just use them at the object creation time:
let objectParameters = {
"current_lang" : "en",
"project_name" : arrayValues[0],
...
}
Well, if you got ordered array and object, here this code might help you:
var obj = {
'first': '1',
'second': '2'
};
var arr = ['first', 'sec'];
Object.keys(obj).forEach(function (key, arrIndex) {
obj[key] = arr[arrIndex];
});
Then you edit and optimize it the way you want.
Little improvement, thank to #Jeremy Thille
If your arrayValues format value will be same then you could use separate keys and use reduce() method for your arrays values and Destructuring_assignment.
DEMO
const keys = ["project_name", "project_type", "min_price", "max_price"],
arrayValues = ["Project name", "Project Type", 150, 950];
let result = arrayValues.reduce((r, v, i) => {
return { ...r,
[keys[i]]: v
}
}, {current_lang:navigator.language});
console.log(result)
.as-console-wrapper {max-height: 100% !important;top: 0;}
Currently, my JSON looks like this:
var json = {"level" : [
{"hs": 20}, //one
{"no_hs": 30} //two
]};
I need it to look like this:
var json = {"level" : [
{"education" : "hs", "amount" : 20}, //one
{"education" : "no_hs", "amount" : 30} //two
]};
How do I split a key value pair, make both values, and then add keys to them?
You can use Object.keys() for getting the keys.
var object = { "level": [{ "hs": 20 }, { "no_hs": 30 }] };
object.level = object.level.map(function (a) {
var o = {};
Object.keys(a).forEach(function (k) {
o.education = k;
o.amount = a[k];
});
return o;
});
document.write('<pre>' + JSON.stringify(object, 0, 4) + '</pre>');
You can use Object.keys(obj) to return an array of keys for a given object. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
Then you access the first key using [0], because your object only has one key-value pair.
var json = {"level" : [
{"hs": 20}, //one
{"no_hs": 30} //two
]};
var ret = [];
json.level.forEach(function (item) {
var key = Object.keys(item)[0];
ret.push({
education: Object.keys(item)[0],
amount: item[key]
});
});
json.level = ret;
document.write('<pre>'+JSON.stringify(json, 0, 4) + '</pre>');
Simpler way to do it...
Resolved with 1 map function...
For each element in the level array, get the first key of the object and return the new element.
var json = {"level" : [
{"hs": 20}, //one
{"no_hs": 30} //two
]};
json.level = json.level.map(function(val) {
var key = Object.keys(val)[0];
return {
education: key,
amount: val[key]
};
});