change key/values of an object - javascript

If I have a result like this:
result = [
{ '0': 'grade', A: 'name', b1: 'number' },
{ '1': 'grade', B: 'name', b2: 'number' },
{ '2': 'grade', C: 'name', b3: 'number' }
];
How can I produce :
result = [
{ A: '0', b1: '0' },
{ B: '1', b2: '1' },
{ C: '2', b3: '2' }
];
I want to pass the analogous grade instead of name and number.

The order of keys in an object is not guaranteed. This means simply getting a key array and looping through them or accessing them by index will not work. You could make this work be detecting numeric and non-numeric keys like so:
result = [
{ '0': 'grade', A: 'name', b1: 'number' },
{ '1': 'grade', B: 'name', b2: 'number' },
{ '2': 'grade', C: 'name', b3: 'number' }
];
result.forEach(item => {
var keys = Object.keys(item);
var numericKey = keys.find(key => !isNaN(key));
var nonNumericKeys = keys.filter(key => isNaN(key));
nonNumericKeys.forEach(nonNumKey => item[nonNumKey] = numericKey);
delete item[numericKey];
});

Assuming the b3: '1' part is a typo... the following should work.
var input = [
{ '0': 'grade', A: 'name', b1: 'number' },
{ '1': 'grade', B: 'name', b2: 'number' },
{ '2': 'grade', C: 'name', b3: 'number' }
];
function reverseMap(obj){
var newObj = {};
var keys = Object.keys(obj);
for(var i=0; i<keys.length; i++){
var k = keys[i];
var v = obj[k];
newObj[v] = k;
}
return newObj;
}
var output = [];
for(var i=0; i<input.length; i++){
var reverseObj = reverseMap(input[i]);
var outputObj = {};
var number = reverseObj.grade;
outputObj[reverseObj.name] = number;
outputObj[reverseObj.number] = number;
output.push(outputObj);
}
console.log(output);

With ES6 you can use the for of loop and Objects.keys for this task:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/let
let newResult = [];
for(let r of result) {
let keys = Object.keys(r);
let obj = {};
for(let key of keys) {
if(/\d/.test(key)) { var value = key; }
else if(/\w/.test(key)) { var key1 = key; }
else if(/\d/.test(key)) { var key2 = key; }
}
obj[key1] = value;
obj[key2] = value;
newResult.push(obj);
}
return newResult;

Related

How to map an array to object

Is there a built-in lodash function to take this:
let params = ['foo', 'bar', 'baz', 'zle'];
let newArray = [];
params.forEach((element, index) => {
let key = "name" + index;
newArray.push({ key: element })
});
console.log(newArray);
And expected output should be like this:
var object = {
a: {
name1: "foo",
name2: "bar",
},
b: {
name1: "baz",
name2: "zle",
}
}
May this help you. I know that you should provide more information that what do really want to implement. but i got an idea that might help you.
let params = ['foo', 'bar', 'baz', 'zle'];
const keys = ['a', 'b', 'c', 'd']
let data = {}
while(params.length){
const [a, b] = params.splice(0, 2)
const key = keys.splice(0, 1)
data[key] = {
name1: a,
name2: b,
}
}
console.log(data)
output will be:
{
a: {
name1: "foo",
name2: "bar",
},
b: {
name1: "baz",
name2: "zle",
}
}
You can convert your array into Json like format that can be done like this
var jsonObj = {};
for (var i = 0 ; i < sampleArray.length; i++) {
jsonObj["position" + (i+1)] = sampleArray[i];
}
I have solved the issue. Solution for this issue is
let colLength = 4;
let breakableArray = _.chunk(data, 4);
breakableArray.forEach((arrayObject,key)=>{
let object = new Object();
for(let i = 0; i < colLength; i++) {
object[i] = arrayObject[i] != undefined ? arrayObject[i] : "-";
}
finalObject[key] = object;
})

How to get value from index property in javascript?

Here is my code:
const array1 = [{a: 'abc', b: 'cd'}, {a: 'abc', b: 'xyz'}, {a: 'abc',
b: 'mno'}];
let obj = array1.reduce(function(result, item, index){
result[index] = item
return result;
}, {});
let dealId = 123;
let value = {};
let array2 = [];
for (var property in obj) {
value[dealId] = array2.push(obj[property]);
}
console.log(value)
The output of this is
Object { 123: 3 }
But I want and this is what I was expecting.
Object { 123: [{a: 'abc', b: 'cd'}, {a: 'abc', b: 'xyz'}, {a: 'abc', b: 'mno'}] }
Why am I getting 3 instead of an array? How to get the array?
Array.prototype.push returns the new length of the array, not the array itself. Your loop assigns the values 1, 2 and 3 to the same value[dealId].
Instead, you can move the assignment outside the loop:
for (var property in obj) {
array2.push(obj[property]);
}
value[dealId] = array2;
Or you can simply use Object.values:
value[dealId] = Object.values(obj);
But note that this does not list inherited properties.
Why not build a new object with a single key and the given array as value?
For the object use a computed property name.
const
array = [{ a: 'abc', b: 'cd' }, { a: 'abc', b: 'xyz' }, { a: 'abc', b: 'mno' }],
key = 123,
object = { [key]: array };
console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }
you need to add into aaray first then create the object
const array1 = [{a: 'abc', b: 'cd'}, {a: 'abc', b: 'xyz'}, {a: 'abc', b: 'mno'}];
let obj = array1.reduce(function(result, item, index){
result[index] = item
return result;
}, {});
let dealId = 123;
let value = {};
let array2 = [];
for (var property in obj) {
array2.push(obj[property]);
}
value[dealId] = array2;
console.log(value);
const array1 = [{a: 'abc', b: 'cd'}, {a: 'abc', b: 'xyz'}, {a: 'abc',
b: 'mno'}];
let obj = array1.reduce(function(result, item, index){
result[index] = item
return result;
}, {});
let dealId = 123;
let value = {};
let array2 = [];
for (var property in obj) {
array2.push(obj[property]);
}
value[dealId] = array2;
console.log(value)
Assign your new obj property (id) the requested array:
let arr = [{a: 'abc', b: 'cd'}, {a: 'abc', b: 'xyz'}, {a: 'abc',
b: 'mno'}];
let newObj = {};
let id = 123;
newObj[id] = arr;
console.log(newObj);

Divide object in array of arrays using keys

Consider the following object :
{ a1: "Foo", b1: "Boo" , c1: "Coo", a2: "Doo" , b2: "Goo", c2: "Soo", ....... c50: "Zoo" }
I want to divide this in an array of arrays that will look like this :
[["Foo","Boo","Coo"], ["Doo","Goo","Soo"]......[ .., ..,"Zoo"]]
What is the best practice for doing that ?
You can first use reduce() on Object.keys() to return one object and then map() keys of that object to return values which will be array of values.
var obj = { a1: "Foo", b1: "Boo" , c1: "Coo", a2: "Doo" , b2:"Goo", c2:"Soo", c50:"Zoo"}
var o = Object.keys(obj).reduce(function(r, e) {
var newKey = e.match(/\d+/)[0]
r[newKey] = (r[newKey] || []).concat(obj[e])
return r
}, {})
var result = Object.keys(o).map(e => o[e])
console.log(result)
With ES-7 you could use Object.values() but it still has bad browser support, but the solution looks like this.
var obj = { a1: "Foo", b1: "Boo" , c1: "Coo", a2: "Doo" , b2:"Goo", c2:"Soo", c50:"Zoo"}
var result = Object.values(Object.keys(obj).reduce(function(r, e) {
var newKey = e.match(/\d+/)[0]
return r[newKey] = (r[newKey] || []).concat(obj[e]), r
}, {}))
console.log(result)
You could get the keys with Object.keys, iterate with Array#forEach over them, get the numerical part with String#match, decrement it for the index and push the value.
var object = { a1: "Foo", b1: "Boo" , c1: "Coo", a2: "Doo" , b2:"Goo", c2:"Soo", c50:"Zoo"},
result = [];
Object.keys(object).forEach(function (key) {
var i = key.match(/\d+$/) - 1;
result[i] = result[i] || [];
result[i].push(object[key]);
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Try something like this:
var obj = { a1: "Foo", b1: "Boo" , c1: "Coo", a2: "Doo" , b2:"Goo", c2:"Soo" };
var indexObj = { a: 0, b: 1, c: 2 };
var result = [];
for(var prop in obj) {
var index = indexObj[prop[0]];
var array = prop.match(/\d+$/) - 1;
if(!result[array]) {
result[array] = [];
}
result[array][index] = obj[prop];
}
console.log(JSON.stringify(result));
//[["Foo","Boo","Coo"],["Doo","Goo","Soo"]]
May be you can do as follows;
var obj = { a1: "Foo", b1: "Boo" , c1: "Coo", a2: "Doo" , b2: "Goo", c2: "Soo", a3: "Hello", b3: "to", c3: "you", c50: "Zoo" },
res = Object.keys(obj)
.reduce(function(r,c){
var t = /\d+/.exec(c)[0];
r.t = r.t !== t ? (r.push([obj[c]]), t)
: (r[r.length-1].push(obj[c]), t);
return r;
},[]);
console.log(res);

Split an object by each value in array inside of it

I have an object that contains a key and an array with some values inside of it.
var obj1 = {
'key': '1',
'values': ['a', 'b', 'c']
}
var obj2 = {
'key': '10',
'values': ['a', 'b']
}
I want to split this in other objects for each value in my values array to result something like this:
obj1 = 'key': '1', 'value':'a', 'index': '0';
obj2 = 'key': '1', 'value':'b', 'index': '1';
obj3 = 'key': '1', 'value':'c', 'index': '2';
obj4 = 'key': '10', 'value': 'a', 'index': '0';
obj5 = 'key': '10', 'value': 'b', 'index': '1';
Any ideas to do this?
Try this example
var brief = function(obj) {
var tmp = [],
i = 0,
l = obj.values.length;
while (i < l)
tmp.push({
key: obj.key,
index: i,
value: obj.values[i++]
});
return tmp;
};
var obj1 = brief({
key: '1',
values: ['a', 'b', 'c']
});
var obj2 = brief({
key: '2',
values: ['a', 'c']
});
document.write("<pre>");
document.write(JSON.stringify(obj1));
document.write("<br/>");
document.write(JSON.stringify(obj2));
document.write("</pre>");
Friend, it would be something like:
tmp = [];
obj1.values.forEach(function (e, i) {
tmp.push({key: obj1.key, value: e, index: i})
});
console.log(tmp);
assuming that you want
obj1 =[ { key: '1', value:'a', index: '0' },
{ key: '1', value:'b', index: '1'},
{ key: '1', value:'c', index: '2' }]
try
function splitArray( obj )
{
var output = [];
var keyValue = obj.key;
var values = obj.values;
for ( var counter = 0; counter < values.length; counter++ )
{
output.push( {
key : keyValue,
value : values[ counter ],
index : counter
} );
}
return output;
}
console.log( splitArray( obj1 ) );
function getTransformedObjects(obj) {
var ans = [];
if (obj.values) {
obj.values.forEach(function(value, index) {
var temp = {
'key': obj.key,
'value': value,
'index': index
};
ans.push(temp);
})
}
return ans;
}
//for display purpose
// usage
var obj1 = {
key: '1',
values: ['a', 'b', 'c']
}
console.log(getTransformedObjects(obj1));
$('.old').html(JSON.stringify(obj1))
$('.new').html(JSON.stringify(getTransformedObjects(obj1)));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div>old object</div>
<div class='old'></div>
<div>Trasnformed object</div>
<div class='new'></div>
Call the function passing the old object as parameter and get the array of objects in required format.

Concatenate two JSON objects

I have two JSON objects with the same structure and I want to concat them together using Javascript. Is there an easy way to do this?
Based on your description in the comments, you'd simply do an array concat:
var jsonArray1 = [{'name': "doug", 'id':5}, {'name': "dofug", 'id':23}];
var jsonArray2 = [{'name': "goud", 'id':1}, {'name': "doaaug", 'id':52}];
jsonArray1 = jsonArray1.concat(jsonArray2);
// jsonArray1 = [{'name': "doug", 'id':5}, {'name': "dofug", 'id':23},
//{'name': "goud", 'id':1}, {'name': "doaaug", 'id':52}];
If you'd rather copy the properties:
var json1 = { value1: '1', value2: '2' };
var json2 = { value2: '4', value3: '3' };
function jsonConcat(o1, o2) {
for (var key in o2) {
o1[key] = o2[key];
}
return o1;
}
var output = {};
output = jsonConcat(output, json1);
output = jsonConcat(output, json2);
Output of above code is{ value1: '1', value2: '4', value3: '3' }
The actual way is using JS Object.assign.
Object.assign(target, ...sources)
MDN Link
There is another object spread operator which is proposed for ES7 and can be used with Babel plugins.
Obj = {...sourceObj1, ...sourceObj2}
I use:
let x = { a: 1, b: 2, c: 3 }
let y = {c: 4, d: 5, e: 6 }
let z = Object.assign(x, y)
console.log(z)
// OUTPUTS:
{ a:1, b:2, c:4, d:5, e:6 }
From here.
You can use jquery extend method.
Example:
o1 = {"foo":"bar", "data":{"id":"1"}};
o2 = {"x":"y"};
sum = $.extend(o1, o2);
Result:
sum = {"foo":"bar", "data":{"id":"1"}, "x":"y"}
One solution is to use a list/array:
var first_json = {"name":"joe", "age":27};
var second_json = {"name":"james", "age":32};
var jsons = new Array();
jsons.push(first_json);
jsons.push(second_json);
Result
jsons = [
{"name":"joe", "age":27},
{"name":"james", "age":32}
]
if using TypeScript, you can use the spread operator (...)
var json = {...json1,...json2}
You can use Object.assign() method. The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.[1]
var o1 = { a: 1 }, o2 = { b: 2 }, o3 = { c: 3 };
var obj = Object.assign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
okay, you can do this in one line of code. you'll need json2.js for this (you probably already have.). the two json objects here are unparsed strings.
json1 = '[{"foo":"bar"},{"bar":"foo"},{"name":"craig"}]';
json2 = '[{"foo":"baz"},{"bar":"fob"},{"name":"george"}]';
concattedjson = JSON.stringify(JSON.parse(json1).concat(JSON.parse(json2)));
Just try this, using underscore
var json1 = [{ value1: '1', value2: '2' },{ value1: '3', value2: '4' }];
var json2 = [{ value3: 'a', value4: 'b' },{ value3: 'c', value4: 'd' }];
var resultArray = [];
json1.forEach(function(obj, index){
resultArray.push(_.extend(obj, json2[index]));
});
console.log("Result Array", resultArray);
Result
var baseArrayOfJsonObjects = [{},{}];
for (var i=0; i<arrayOfJsonObjectsFromAjax.length; i++) {
baseArrayOfJsonObjects.push(arrayOfJsonObjectsFromAjax[i]);
}
I use:
let jsonFile = {};
let schemaJson = {};
schemaJson["properties"] = {};
schemaJson["properties"]["key"] = "value";
jsonFile.concat(schemaJson);
The simplest way :
const json1 = { value1: '1', value2: '2' };
const json2 = { value2: '4', value3: '3' };
const combinedData = {
json1,
json2
};
console.log(combinedData)
I dont know if you want this:
U can use this for create from arrays, all arrays need contains the same number of elments.
Example:
If you have:
let a = ["a", "b", "c"];
let b = [1, 2, 3];
Use
concatArraysLikeJson([a, b]);
The result of is:
let result = {
0 : ["a", 1],
1 : ["b", 2],
2 : ["c", 3]
};
Typescript
concatArraysLikeJson(arrays:any){
let result:any = {};
let size:number = 0;
let make:boolean = true;
if(arrays.length > 0){
size = arrays[0].length;
for(let i = 1; i < arrays.length; i++){
let array = arrays[i];
if(make){
if(array.length != size){
make = false;
}
}
}
}
if(make){
for (let o = 0; o < size; o++) {
result[o] = [];
}
for(let i = 0; i < arrays.length; i++){
const array = arrays[i];
//console.log(array);
for (let o = 0; o < size; o++) {
const element = array[o];
result[o].push(element);
}
}
return result;
}else{
return false;
}
}
Javascript:
concatArraysLikeJson(arrays){
let result = {};
let size = 0;
let make = true;
if(arrays.length > 0){
size = arrays[0].length;
for(let i = 1; i < arrays.length; i++){
let array = arrays[i];
if(make){
if(array.length != size){
make = false;
}
}
}
}
if(make){
for (let o = 0; o < size; o++) {
result[o] = [];
}
for(let i = 0; i < arrays.length; i++){
const array = arrays[i];
//console.log(array);
for (let o = 0; o < size; o++) {
const element = array[o];
result[o].push(element);
}
}
return result;
}else{
return false;
}
}
The JSON Objects and Arrays can be combined in multiple ways within a structure
I can merge json with rules using json-object-merge
import JSONObjectMerge from "json-object-merge";
const target = {
store: {
book: [
{
category: "reference",
author: "Nigel Rees",
title: "Sayings of the Century",
price: 8.95
}
],
bicycle: {
color: "red",
price: 19.95
}
}
};
const source = {
store: {
book: [
{
category: "fiction",
author: "Evelyn Waugh",
title: "Sword of Honour",
isbn: "0-679-43136-5",
price: 12.99
}
]
}
};
const merged = JSONObjectMerge(target, source, { "$.store.book": "PREPEND" });
expect(merged).toEqual({
store: {
book: [
{
// books from source are prepended to the original array
category: "fiction",
author: "Evelyn Waugh",
title: "Sword of Honour",
isbn: "0-679-43136-5",
price: 12.99
},
{
category: "reference",
author: "Nigel Rees",
title: "Sayings of the Century",
price: 8.95
}
],
bicycle: {
color: "red",
price: 19.95
}
}
});

Categories

Resources