How to convert an object into nested object - javascript

How can I transform the following:
{
Eldoret: "900",
Nairobi: "1900"
}
into:
[
{
y:"Eldoret",
a: 900
},
{
y:"Nairobi",
a:1900
}
]
using JavaScript. I've tried using the following snippet but it just picks on the last property
for(var key in data3){
if(data3.hasOwnProperty(key)){
data_obj.y = key;
data_obj.a = data3[key];
}
Output:
{
y: "Nairobi",
a: "1900"
}

You iterate over your keys:
var myobj = { .... };
var objKeys = Object.keys(myobj);
var reformatted = objKeys.map(function(key) {
return {
x: key,
y: myobj[key]
};
});

You can build up the result step-by-step by appending items to a new array in your loop:
data3 = {
Eldoret: "900",
Nairobi: "1900"
}
res = []
for (var key in data3) {
res.push({
y: key,
a: data3[key],
})
}
console.log(res)

Related

How to add key value pair in an JSON dynamically using Lodash or JS in reactJS?

I have JSON like this:
let json = {
data:[
{value1: 1},
{Value2: 2}
]
}
maths:100
science:100
I need to add these two key value pairs to the json:
let json = {
data:[
{value1:1},
{Value2:2}
],
maths:100,
science:100
}
You can do like this:
let json = {
data:[{value1:1},{Value2:2}]
}
console.log({...json, maths: 100, science: 100})
If you are expecting this output
{"data":[{"value1":1},{"Value2":2}],"maths":100,"science":100}
You can check the following code
let json = {
"data":[
{
"value1":1
},{
"Value2":2
}
]
}
function pushToAry(name, val) {
var obj = {};
json[name] = val;
}
pushToAry("maths", 100);
pushToAry("science", 100);
console.log(JSON.stringify(json));
Else, If you are expecting the below output
{"data":[{"value1":1},{"Value2":2},{"maths":100},{"science":100}]}
You can check the following code
let json = {
"data":[
{
"value1":1
},{
"Value2":2
}
]
}
function pushToAry(name, val) {
var obj = {};
obj[name] = val;
json["data"].push(obj);
}
pushToAry("maths", 100);
pushToAry("science", 100);
console.log(JSON.stringify(json));

JavaScript: How to convert nested array of object to key-value pair objects

It can be duplicate question but i have tried a lot but i did not get expected result.Could some one help me.
I am getting an array in request body like :
[
{
"name":"array",
"book":[
{
"name":"name1",
"book":"book1"
},
{
"name":"name2",
"book":"book2"
}
]
},
{
"name":"name3",
"book":"book3"
}
]
And I need to convert the array of nested array to below format
{
array: [
{
name1: "book1"
},
{
name2: "book2"
}
],
name3: "book3"
}
Note:In some cases book can be array or string.
On my first attempt i have tried below code to convert it into single object but it doest not convert nested array to key value pair
const array=[
{
"name":"array",
"book":[
{
"name":"name1",
"book":"book1"
},
{
"name":"name2",
"book":"book2"
}
]
},
{
"name":"name3",
"book":"book3"
}
]
var result = {};
for (var i = 0; i < array.length; i++) {
result[array[i].name] = array[i].value;
}
console.log(result);
Response for the above code
{
array: [
{
name: "name1",
book: "book1"
},
{
name: "name2",
book: "book2"
}
],
name3: "book3"
}
EDITED
I have made little change in the Code from the Ahmed's answer and it worked
const res=[
{
"name":"array",
"book":[
{
"name":"name1",
"book":"book1"
},
{
"name":"name2",
"book":"book2"
}
]
},
{
"name":"name3",
"book":"book3"
}
]
const obj = {}
for(let i = 0 ; i < res.length; i++){
let name = res[i].name
if(Array.isArray(res[i]['book'])){
obj[name] = [];
for(let item in res[i]['book']){
let key = res[i]['book'][item]['name']
let value = res[i]['book'][item]['book']
let entry = {}
entry[key] = value
obj[name].push(entry)
}
}
else{
obj[res[i].name]=res[i].book;
}
}
console.log(obj);
The added snippet should solve your problem.
The problem in your code was Appropriate nesting you didn't access the wanted values and didn't handle all the cases Hence, The wrong output.
const res = [
{
"name":"array",
"book":[
{
"name":"name1",
"book":"book1"
},
{
"name":"name2",
"book":"book2"
}
]
},
{
"name":"name3",
"book":"book3"
}
]
const obj = {}
for(let i = 0 ; i < res.length; i++){
let name = res[i].name
if(Array.isArray(res[i]['book'])){
obj[name] = []
for(let item in res[i]['book']){
let key = res[i]['book'][item]['name']
let value = res[i]['book'][item]['book']
let entry = {}
entry[key] = value
obj[name].push(entry)
}
}
else{
obj[name] = res[i]['book']
}
}
for(let item in obj){
console.log(item)
console.log(obj[item])
}

Push different value at each element of JSON

I have a array "derniere" with 3 value and in my json I have 3 elements.
I want push the value according to the cle (look responseTime).
The iteration for the json is good but i'm blocked for the iteration of the variable "derniere"
var arr = [
{ "cle": "1" },
{ "cle": "2" },
{ "cle": "3" }
]
for (const key in arr) {
var key_t = arr[key].cle
derniere = [200, 1000, 400]
function showNextKey(arr, compteur, callback, time) {
callback(arr[compteur].cle);
compteur++;
if (compteur < arr.length) {
setTimeout(showNextKey, time, arr, compteur, callback, time);
}
};
}
function sender(cle) {
const gekoq = require('gekoq');
const push = gekoq('*****'); // Geckoboard API Key
for(key2 in derniere){
push({
key: cle, // Widget Key
data: {
"responseTime": derniere[key2]
}
})
.then(response => console.log(response));
console.log();
}
}
setTimeout(showNextKey, 2000, arr, 0, sender, 2000);
Actual result:
Cle(1):
Cle(2):
Cle(3):
Expected results:
Cle(1): 200
Cle(2): 1000
Cle(3): 400
You can use reduce method over the input array and build keys associating the corresponding values of derniere array:
const inp = [{
"cle": "1"
},
{
"cle": "2"
},
{
"cle": "3"
}
];
const derniere = [200, 1000, 400];
console.log(inp.reduce((acc, val, ind) => acc.concat({ [`Cle(${[val['cle']]})`]: derniere[ind] }), []));
Not sure if this is what you're looking for.. but it seems to create the expected result.
Basically i just used the map function after destructuring the array into two separate arrays in order to standardize the data structure..
var arr = [{
"cle": "1"
},
{
"cle": "2"
},
{
"cle": "3"
}
]
var derniere = [200, 1000, 400];
(function() {
var cle = arr.map((item) => {
return item["cle"]
});
var result = {
_derniere: derniere,
_cle: cle
};
console.log(result._cle.map((item, idx) => {
var obj = {};
obj[item] = result._derniere[idx];
return obj;
}));
})();
var arr = [
{ "cle": "1" },
{ "cle": "2" },
{ "cle": "3" }
]
for (const key in arr) {
var key_t = arr[key].cle
derniere = [200, 1000, 400]
function showNextKey(arr, compteur, callback, time) {
callback(arr[compteur].cle);
compteur++;
if (compteur < arr.length) {
setTimeout(showNextKey, time, arr, compteur, callback, time);
}
};
}
function sender(cle) {
const gekoq = require('gekoq');
const push = gekoq('*****'); // Geckoboard API Key
push({
key: cle, // Widget Key
data: {
"responseTime": derniere.shift()
}
})
.then(response => console.log(response));
console.log();
}
setTimeout(showNextKey, 2000, arr, 0, sender, 2000)

How can I add name to existing value pair in json

Hello this is my sample json:
{
"2016-01-01T00:00:00Z": 1,
"2016-02-01T00:00:00Z": 2,
"2016-03-01T00:00:00Z": 3
}
Now I want something like
[
{"Month":"2016-01-01T00:00:00Z", "Number": 1},
{"Month":"2016-02-01T00:00:00Z", "Number": 2},
{"Month":"2016-03-01T00:00:00Z", "Number": 3}
]
How can I do this using JS/Jquery? I wanted to change it to the above mentioned format because I need to put them in html table and I found out that using the second format makes my job easier.
you can do this in the following way
let obj = {
"2016-01-01T00:00:00Z": 1,
"2016-02-01T00:00:00Z": 2,
"2016-03-01T00:00:00Z": 3
};
let result = [];
for(element in obj){
result.push({"Month":element, "Number": obj[element]})
}
console.log(result);
You can use the jQuery map function to change the format of an array.
let jsonArray = {
"2016-01-01T00:00:00Z": 1,
"2016-02-01T00:00:00Z": 2,
"2016-03-01T00:00:00Z": 3
};
var result = $.map(jsonArray, function (item, key) {
return {
Month: key,
Number: item
};
});
You could take the keys with Object.keys and use Array#map for mapping the new objects.
var object = { "2016-01-01T00:00:00Z": 1, "2016-02-01T00:00:00Z": 2, "2016-03-01T00:00:00Z": 3 },
result = Object.keys(object).map(function (k) {
return { Month: k, Number: object[k] };
});
console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
var object1 = {
"2016-01-01T00:00:00Z": 1,
"2016-02-01T00:00:00Z": 2,
"2016-03-01T00:00:00Z": 3
};
var finalArray = [];
for (var key in object1) {
if (p.hasOwnProperty(key)) { // p.hasOwnProperty this will check for duplicate key
finalArray.push({
“Month” : key,
“Number”:p[key]
});
}
}
console.log(finalArray)
Another option could include using Object.keys along with map as such...
let obj = {
'2016-01-01T00:00:00Z': 1,
'2016-02-01T00:00:00Z': 2,
'2016-03-01T00:00:00Z': 3
}
let arr = Object.keys(obj).map(key => {
return {'Month': key, 'Number': obj[key]}
});
JSFiddle demo
use $.each for travelling
a = {
"2016-01-01T00:00:00Z": 1,
"2016-02-01T00:00:00Z": 2,
"2016-03-01T00:00:00Z": 3
}
var b = [];
$.each( a, function( key, value ) {
b.push({mounth: key ,number: value });
});
Output will be:
0:{mounth: "2016-01-01T00:00:00Z", number: 1}
1:{mounth: "2016-02-01T00:00:00Z", number: 2}
2:{mounth: "2016-03-01T00:00:00Z", number: 3}

Javascript Fill array with missing object and value

I have an array like bellow each index contains different set of objects,I want to create an uniformal data where object missing in each index will with Value:0 ,
var d = [
[
{axis:"Email",value:59,id:1},
{axis:"Social Networks",value:56,id:2},
],
[
{axis:"Sending Money",value:18,id:6},
{axis:"Other",value:15,id:7},
]
];
how can I get an array like bellow using above above array
var d = [
[
{axis:"Email",value:59,id:1},
{axis:"Social Networks",value:56,id:2},
{axis:"Sending Money",value:0,id:6},
{axis:"Other",value:0,id:7},
],
[
{axis:"Email",value:0,id:1},
{axis:"Social Networks",value:0,id:2},
{axis:"Sending Money",value:18,id:6},
{axis:"Other",value:15,id:7},
]
];
There are two functions:
getAllEntries that find all objects and stores them into a variable accEntries. Then accEntries is used to search for all occurrences in a sub-array of d. This whole process is done in checkArray.
checkArray is used to fetch all found and not-found entries in d. Both Arrays (found and not-found) are then used to build a new sub-array that contains either found entries with certain values and/or not-found entries with values of 0.
Hope this helps:
var d = [
[
{
axis: 'Email',
value: 59,
id: 1
},
{
axis: 'Social Networks',
value: 56,
id: 2
},
],
[
{
axis: 'Sending Money',
value: 18,
id: 6
},
{
axis: 'Other',
value: 15,
id: 7
},
]
];
function getAllEntries(array) {
var uniqueEntries = [];
array.forEach(function (subarray) {
subarray.forEach(function (obj) {
if (uniqueEntries.indexOf(obj) === - 1) uniqueEntries.push(obj);
});
});
return uniqueEntries;
}
function checkArray(array, acceptedEntries) {
var result = [];
array.forEach(function (subArray) {
var subResult = [];
var foundEntries = [];
subArray.forEach(function (obj) {
if (foundEntries.indexOf(obj.axis) === - 1) foundEntries.push(obj.axis);
});
var notFound = acceptedEntries.filter(function (accepted) {
return foundEntries.indexOf(accepted.axis) === - 1;
});
foundEntries.forEach(function (found) {
subArray.forEach(function (obj) {
if (obj.axis === found) subResult.push(obj);
});
});
notFound.forEach(function (notfound, index) {
subResult.push({
axis: notfound.axis,
value: 0,
id: notfound.id
});
});
result.push(subResult);
});
return result;
}
var accEntries = getAllEntries(d);
var result = checkArray(d, accEntries);
console.log(result);
You can loop over the array to find all the unique objects and then again loop over to push the values that are not present comparing with the array of objects of unique keys.
You can use ES6 syntax to find if an object with an attribute is present like uniKeys.findIndex(obj => obj.axis === val.axis); and the to push with a zero value use the spread syntax like d[index].push({...val, value: 0});
Below is the snippet for the implementation
var d = [
[
{axis:"Email",value:59,id:1},
{axis:"Social Networks",value:56,id:2},
],
[
{axis:"Sending Money",value:18,id:6},
{axis:"Other",value:15,id:7},
{axis:"Social Networks",value:89,id:2},
]
];
var uniKeys = [];
$.each(d, function(index, item) {
$.each(item, function(idx, val){
const pos = uniKeys.findIndex(obj => obj.axis === val.axis);
if(pos == - 1) {
uniKeys.push(val);
}
})
})
$.each(d, function(index, item) {
var temp = [];
$.each(uniKeys, function(idx, val){
const pos = item.findIndex(obj => obj.axis === val.axis);
if(pos == - 1) {
d[index].push({...val, value: 0});
}
})
})
console.log(d);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
How about a short shallowCopy function (Object.assign is not available in IE) and otherwise less than 10 new lines of code?
var d = [
[
{axis:"Email",value:59,id:1},
{axis:"Social Networks",value:56,id:2}
],
[
{axis:"Sending Money",value:18,id:6},
{axis:"Other",value:15,id:7}
]
];
var newD_0 = [shallowCopy(d[0][0]), shallowCopy(d[0][1]), shallowCopy(d[1][0]), shallowCopy(d[1][1])];
var newD_1 = [shallowCopy(d[0][0]), shallowCopy(d[0][1]), shallowCopy(d[1][0]), shallowCopy(d[1][1])];
newD_0[2].id = 0;
newD_0[3].id = 0;
newD_1[0].id = 0;
newD_1[1].id = 0;
d = [newD_0, newD_1];
function shallowCopy(obj) {
var copy = {};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
copy[key] = obj[key];
}
}
return copy;
}
console.log(JSON.stringify(d));
RESULT:
[
[
{
"axis":"Email",
"value":59,
"id":1
},
{
"axis":"Social Networks",
"value":56,
"id":2
},
{
"axis":"Sending Money",
"value":18,
"id":0
},
{
"axis":"Other",
"value":15,
"id":0
}
],
[
{
"axis":"Email",
"value":59,
"id":0
},
{
"axis":"Social Networks",
"value":56,
"id":0
},
{
"axis":"Sending Money",
"value":18,
"id":6
},
{
"axis":"Other",
"value":15,
"id":7
}
]
]

Categories

Resources