When I write Javascript, I want to read all the data of the device into the object, but only the last one is read.
I would like to ask how I can read all the data in the device into obj, thank you.
let data = [
{
"bind": "82218018295591013",
"account": "admin",
"password": "0000",
"devices": [
{
"ip": "192.168.0.88",
"brand_name": "UNIVIEW",
"name": "UNIVIEW"
}
]
},
{
"bind": "94907378021478863",
"account": "admin",
"password": "0000",
"devices": [
{
"ip": "192.168.0.88",
"brand_name": "UNIVIEW",
"name": "UNIVIEW"
},
{
"ip": "192.168.0.89",
"brand_name": "hisharp",
"name": "hisharp"
}
]
}
]
let obj = {};
function getObj() {
for (let i = 0; i < data.length; i++) {
for (let j = 0; j < data[i].devices.length; j++) {
obj.devices = data[i].devices[j];
}
}
return obj;
}
console.log('obj :>> ', obj);
getObj();
You are having a single object for all objects and you store all objects, but the problem is that each time that you store an object, you are overriding the previous one with it.
function getObj(obj) {
obj.devices = [];
for (let i = 0; i < data.length; i++) {
obj.devices.concat(data[i].devices);
}
return obj;
}
and pass obj:
getObj(obj);
console.log('obj :>> ', obj);
Related
I am trying to transform an object or in other words I am trying change text of an object.
I have two object one is source and another is mapped object.using mapped object I want o transform the source object.
example
source object
{
"links": {
"Offering": {
"id":"offering-id",
"iconUrl": "",
"links": [
{
"text": "School",
"id":"school-id",
"onclickUrl": "https://www.school.com/school/"
},
{
"text": "happy",
"onclickUrl": "https://www.happy.com/help/",
"id":"happy-id"
}
]
},
"luck": {
"iconUrl": "",
"id":"hospital-id",
"links": [
{
"text": "Student",
"id":"student-id",
"onclickUrl": "https://www.student.com/school/"
}
]
}
}
}
mapped -object
let mappingObj = {
"hospital-id":"hospital-change",
"school-id":"school-change-xx",
"offering-id":"Offering-changes-map",
"happy-id":"happy-cs",
"student-id":"nnnnnn"
}
expectedout output
let expectedOutput = {
"links": {
"Offering-changes-map": {
"id":"offering-id",
"iconUrl": "",
"links": [
{
"text": "school-change-xx",
"id":"school-id",
"onclickUrl": "https://www.school.com/school/"
},
{
"text": "happy-cs",
"onclickUrl": "https://www.happy.com/help/",
"id":"happy-id"
}
]
},
"hospital-change": {
"iconUrl": "",
"id":"hospital-id",
"links": [
{
"text": "nnnnnn",
"id":"student-id",
"onclickUrl": "https://www.student.com/school/"
}
]
}
}
}
I have id's in source obj same id's are present in mapped obj.using this I want to change the text of all properties and keys.
I tried like that here is my whole code
https://jsbin.com/zaxoyineme/edit?js,console,output
let result = {};
function recursiveFn(Obj){
for(let i in Obj){
result[mappingObj[Obj[i].id] || i]=Obj[i];
if(typeof Obj[i]==="object"){
console.log('--obj--');
recursiveFn(Obj[i]);
}else if(Object.prototype.toString.call(Obj[i]) === '[object Array]'){
console.log('--Array--');
for(var k =0 ;k<Obj[i].length;k++){
Obj[i].text = result[mappingObj[Obj[i].id] || Obj[i].text]
}
}
}
}
for(let i in Obj){
result[mappingObj[Obj[i].id] || i]=Obj[i];
if(typeof Obj[i]==="object"){
console.log('----');
recursiveFn(Obj[i])
}else if(Object.prototype.toString.call(Obj[i]) === '[object Array]'){
console.log('--Array--');
for(var k =0 ;k<Obj[i].length;k++){
Obj[i].text = result[mappingObj[Obj[i].id] || Obj[i].text]
}
}
}
console.log(JSON.stringify(result))
I am using recession to get the expected output.but I am not able to get the expected output
Your code is way to complicated for what you are trying to do. From What I understood this should probably do your job.
let Obj = {
"links": {
"Offering": {
"id":"offering-id",
"iconUrl": "",
"links": [
{
"text": "School",
"id":"school-id",
"onclickUrl": "https://www.school.com/school/"
},
{
"text": "happy",
"onclickUrl": "https://www.happy.com/help/",
"id":"happy-id"
}
]
},
"luck": {
"iconUrl": "",
"id":"hospital-id",
"links": [
{
"text": "Student",
"id":"student-id",
"onclickUrl": "https://www.student.com/school/"
}
]
}
}
}
let mappingObj = {
"hospital-id":"hospital-change",
"school-id":"school-change-xx",
"offering-id":"Offering-changes-map",
"happy-id":"happy-cs",
"student-id":"nnnnnn"
}
// expected output
let expectedOutput = {
"links": {
"Offering-changes-map": {
"id":"offering-id",
"iconUrl": "",
"links": [
{
"text": "school-change-xx",
"id":"school-id",
"onclickUrl": "https://www.school.com/school/"
},
{
"text": "happy-cs",
"onclickUrl": "https://www.happy.com/help/",
"id":"happy-id"
}
]
},
"hospital-change": {
"iconUrl": "",
"id":"hospital-id",
"links": [
{
"text": "nnnnnn",
"id":"student-id",
"onclickUrl": "https://www.student.com/school/"
}
]
}
}
}
let result = {};
let midResult = {};
function updateObject (Obj) {
let i = 0;
let parseArray = Object.keys(Obj.links);
for (i =0; i < parseArray.length; i++) {
let id = parseArray[i]
let matchingId = mappingObj[Obj.links[id].id]
midResult[matchingId] = Object.assign({}, Obj.links[id])
}
}
updateObject(Obj);
result.links = Object.assign({}, midResult)
console.log(result)
I need to transform below Json array to another array as mentioned below using angularjs/ javascript.
Input Array = [{"Name":"123", "Type": "Type1", "Total":"24"}, {"Name":"123", "Type": "Type2", "Total":"25"}, {"Name":"124", "Type": "Type1", "Total":"26"}, {"Name":"124", "Type": "Type2", "Total":"27"}]
Output Array: [{"Name":"123", "Type1":"24", "Type2":"25"}, {"Name":"124", "Type1":"26", "Type2":"27"}
I would work it out with reduce function I've added some comments for you inside as well:
let inputArray = [{"Name":"123", "Type": "Type1", "Total":"24"}, {"Name":"123", "Type": "Type2", "Total":"25"}, {"Name":"124", "Type": "Type1", "Total":"26"}, {"Name":"124", "Type": "Type2", "Total":"27"}];
// and do reduce function on it
inputArray.reduce((prevVal, currVal, index) => {
// first check if there's Name in already
if (prevVal.find(x => x.Name === currVal.Name)) {
// if there's a Name same as current element use new type as a key and add Total
prevVal.find(x => x.Name === currVal.Name)[currVal.Type] = currVal.Total;
} else {
// in case there's no Name then just create object with it
prevVal.push({
Name: currVal.Name,
[currVal.Type]: currVal.Total
});
}
return prevVal;
}, []);
Here's fiddle:
https://jsfiddle.net/pegla/s9hwbth4/
All you have to do is, get the unique objects from the original list based on Name.
var obj = [{
"Name": "123",
"Type": "Type1",
"Total": "24"
},
{
"Name": "123",
"Type": "Type2",
"Total": "25"
},
{
"Name": "124",
"Type": "Type1",
"Total": "26"
},
{
"Name": "124",
"Type": "Type2",
"Total": "27"
}
];
var getIndex = function(list, property, object) {
for (var i = 0; i < list.length; i++) {
if (list[i][property] == object[property]) {
return i;
}
}
return -1;
}
var result = [];
for (var i = 0; i < obj.length; i++) {
/* Call getIndex to return the index of element in the result and add the type name property */
var index = getIndex(result, 'Name', obj[i]);
if (index != -1) {
result[index][obj[i].Type] = obj[i].Total;
} else {
var newObj = {};
newObj.Name = obj[i].Name;
newObj[obj[i].Type] = obj[i].Total;
result.push(newObj);
}
}
console.log(result);
You don't need angularjs to do that. You can do that using simple javascript for block. Please see attached code. Best,
let input = [{"Name":"123", "Type": "Type1", "Total":"24"}, {"Name":"123", "Type": "Type2", "Total":"25"}, {"Name":"124", "Type": "Type1", "Total":"26"}, {"Name":"124", "Type": "Type2", "Total":"27"}];
let output = [];
for(let i=0; i<input.length-1;i++){
output.push({
"Name":input[i].Name,
"Type1":input[i].Total,
"Type2":input[i+1].Total,
});
i++;
}
console.log(output);
I have this array that needs to be parsed into a useful object. The names of each value are a collection of namespaces separated by / characters. The values between each '/' need to be turned into a JS Objects property:
"status": [
{
"message": "OK",
"name": "/Computer",
"values": []
},
{
"name": "/Computer/CPU Usage",
"values": []
},
{
"name": "/Computer/CPU Temp",
"values": []
},
{
"name": "/Computer/hardware/memory",
"values": []
}
]
I need it to become this:
"status": {
"computer": {
"CPU Usage": {
"values": []
},
"CPU Temp": {
"values": []
},
"hardware": {
"memory": {
"values": []
}
}
}
}
So far I have done this:
var statii = status, // from above..
_parsedStatii = {};
for (var i = 0; statii.length < 0; i ++) {
var _nameSpaces = statii[i].name.split('/');
// Start at 1 because index 0 is empty (before the first slash)
if (!_parsedStatii[_nameSpaces[1]]) {
_parsedStatii[_nameSpaces[1]] = {};
}
if (!_parsedStatii[_nameSpaces[1]][_nameSpaces[2]])
_parsedStatii[_nameSpaces[1]][_nameSpaces[2]] = {};
if (!_parsedStatii[_nameSpaces[1]][_nameSpaces[2]][_nameSpaces[3]])
_parsedStatii[_nameSpaces[1]][_nameSpaces[2]][_nameSpaces[3]] = {};
if (!_parsedStatii[_nameSpaces[1]][_nameSpaces[2]][_nameSpaces[3]][_nameSpaces[4]])
_parsedStatii[_nameSpaces[1]][_nameSpaces[2]][_nameSpaces[3]][_nameSpaces[4]] = {};
}
Obviously it is no where near right, I have tried a lot of recursive functions but am at a bit of a loss. This example gives the clearest representation of what I am trying to achieve. Any ideas? (Please excuse code typos, it was paraphrased)
You could split the name and build an object upon.
var data = { "status": [{ "message": "OK", "name": "/Computer", "values": [] }, { "name": "/Computer/CPU Usage", "values": [] }, { "name": "/Computer/CPU Temp", "values": [] }, { "name": "/Computer/hardware/memory", "values": [] }] },
object = {};
data.status.forEach(function (a) {
a.name.slice(1).split('/').reduce(function (o, k) {
return o[k] = o[k] || {};
}, object).values = a.values;
});
console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }
i want to create jSon format from this string value:
hello|world|this|is|javascript || my|name|is|mahdi
in created jSon array from that i can not wrap this string to separator as 2 array by split with ||. my code is work fine but i can not create some array in json after split string with ||.
result my code is:
{
"FILEDS": [
{
"template_id": "123",
"fields_id": "456"
},
{
"item": "hello"
},
{
"item": "world"
},
{
"item": "this"
},
{
"item": "is"
},
{
"item": "javascript "
},
{
"item": " my"
},
{
"item": "name"
},
{
"item": "is"
},
{
"item": "mahdi"
}
]
}
but i want to have this result like with below json format:
{
"FILEDS": [
{
"template_id": "123",
"fields_id": "456"
},
[
{
"item": "hello"
},
{
"item": "world"
},
{
"item": "this"
},
{
"item": "is"
},
{
"item": "javascript "
}
],
[
{
"item": " my"
},
{
"item": "name"
},
{
"item": "is"
},
{
"item": "mahdi"
}
]
]
}
My code is below code and how to create this array in each for for some data to create and wrap to []?
<script type="text/javascript" language="JavaScript">
var data = "hello|world|this|is|javascript || my|name|is|mahdi";
var templates = {
FILEDS: []
};
templates.FILEDS.push({
"template_id": "123",
"fields_id": "456",
});
var split_data = data.split("||");
for (var i = 0; i < split_data.length; i++) {
var fields = split_data[i].split("|");
for (var j = 0; j < fields.length; j++) {
templates.FILEDS.push({
"item": fields[j],
});
}
}
console.log(JSON.stringify(templates));
</script>
Try this;
var split_data = data.split("||");
for (var i = 0; i < split_data.length; i++) {
var sentence = [];
var fields = split_data[i].split("|");
for (var j = 0; j < fields.length; j++) {
sentence.push({
"item": fields[j],
});
}
templates.FILEDS.push(sentence)
}
You'll need a secondary array to hold the data.
var data = "hello|world|this|is|javascript || my|name|is|mahdi";
var templates = {
FILEDS: []
};
templates.FILEDS.push({
"template_id": "123",
"fields_id": "456",
});
var split_data = data.split("||");
for (var i = 0; i < split_data.length; i++) {
var fields = split_data[i].split("|");
var arr = [];
for (var j = 0; j < fields.length; j++) {
arr.push({ "item" : fields[j] });
}
templates.FILEDS.push(arr);
}
console.log(JSON.stringify(templates));
// result" {"FILEDS":[{"template_id":"123","fields_id":"456"},[{"item":"hello"},{"item":"world"},{"item":"this"},{"item":"is"},{"item":"javascript "}],[{"item":" my"},{"item":"name"},{"item":"is"},{"item":"mahdi"}]]}
Yet another variant with Array.map
[].push.apply(templates.FILEDS, data.split("||").map(function(el){
return el.split('|').map(function(item){
return { "item" : item };
})
}));
UPDATE if you want objects like
{ "FILEDS": [
{ "template_id": "123", "fields_id": "456" },
{"items": [
[ "hello", "world", "this", "is", "javascript " ],
[ " my", "name", "is", "mahdi" ]
] }
]}
you can a bit change code above
templates.FILEDS.push({
"item" : data.split("||").map(function(el){
return el.split('|');
})
}
);
I would like to convert Json data to an array Javascript, that I can access like using array[0][0], someone can help me please.
[
{
"Login": "test1",
"Nom": "test1",
"Prenom": "test1p",
"password": "124564",
"Email": "test1#gmail.com"
},
{
"Login": "test2",
"Nom": "test2",
"Prenom": "test2p",
"password": "124564",
"Email": "test2#gmail.com"
}
]
I tried this piece of code but nothing happen , I can't access to a specific(Exemple I would like to have Nom) data in array using for example array[0][1].
Code.js
var data = [
{
"Login": "test1",
"Nom": "test1",
"Prenom": "test1p",
"password": "1267846",
"Email": "test1#gmail.com"
},
{
"Login": "test2",
"Nom": "test2",
"Prenom": "test2p",
"password": "124494",
"Email": "test2#gmail.com"
}
];
function data_to_array(data) {
var array = [];
for (var key in data) {
var value = data[key];
if (typeof value === 'string') {
array[key] = value;
} else {
array[key] = data_to_array(value);
}
}
return array;
}
var array = data_to_array(data);
for(var i in array)
console.log(array[i]);
Once parsed, if I try to access it using myArr[0][1], it shows as undefined.
var arr = [];
for (var i=0, len=data.length, tmp; i<len; i++) {
tmp = [];
for (var k in data[i]) {
if (data[i].hasOwnProperty(k)) {
tmp.push(data[i][k]);
}
}
arr.push(tmp);
}
arr;
// [
// ["test1","test1","test1p","124564","test1#gmail.com"],
// ["test2","test2","test2p","124564","test2#gmail.com"]
// ]
If you can rely on es5 functions, you can use Array.prototype.map and Object.keys
var arr = data.map(function(e) {
return Object.keys(e).map(function(k) { return e[k]; });
});
arr;
// [
// ["test1","test1","test1p","124564","test1#gmail.com"],
// ["test2","test2","test2p","124564","test2#gmail.com"]
// ]
you have confused with the array and objects. All arrays are objects. but not all objects are arrays. You use "for..in" loop in wrong understanding on array containing objects.
If you add more console statements and check, you can understand how it works. Let me give reqd. solution for your scenario.
var data = [
{
"Login": "test1",
"Nom": "test1",
"Prenom": "test1p",
"password": "1267846",
"Email": "test1#gmail.com"
},
{
"Login": "test2",
"Nom": "test2",
"Prenom": "test2p",
"password": "124494",
"Email": "test2#gmail.com"
}
];
function data_to_array(data) {
var array = [];
for (var i=0;i<data.length;i++) {
var obj = data[i];
array[i] = new Array();
for(var key in obj) {
array[i].push(obj[key]);
}
}
return array;
}
var array = data_to_array(data);
console.log(array);