Concat JSON object into array - javascript

How can I concat JSON objects if the first object is:
{
"total": "2"
}
And second:
[
"player1": {
"score": "100",
"ping": "50"
},
"player2": {
"score": "100",
"ping": "50"
}
]
If I want final result to look like:
{
"total": "2",
{
"player1": {
"score": "100",
"ping": "50"
},
"player2": {
"score": "100",
"ping": "50"
}
}
}
I am trying to do it in JavaScript.
Update
The final result is not a valid array.
What about this?
{
[
"player1": {
"score": "100",
"ping": "50"
},
"player2": {
"score": "100",
"ping": "50"
}
]
}

Your json is not valid. If you want something valid, you need to do something like
{
"total": "2",
"players": [
"player1": {
"score": "100",
"ping": "50"
},
"player2": {
"score": "100",
"ping": "50"
}
]
}

As I've said in the comments,
you're trying to append an invalid Array getting as a result an invalid JSON tree.
To validate an expected JSON you can test it here: http://jsonlint.com/
What's wrong 1:
[ "player1" : { "score": "100", "ping": "50"} ] // Array ??
^ invalid delimiter (should be ,)
What's wrong 2 in the expected result:
{
"property" : "value" ,
"total" : "2" ,
{ "player1" : { "score": "100", "ping": "50" }
^^^^^ where's the property here???
}
What you can do:
var myObject = {"total":"2"};
var players = {
"player1": {
"score": "100",
"ping": "50"
},
"player2": {
"score": "100",
"ping": "50"
}
};
myObject.players = players;
console.log( myObject );
which will result in:
[object Object] {
players: [object Object] {
player1: [object Object] { ... },
player2: [object Object] { ... }
},
total: "2"
}
Object Literal needs a comma separated PROPERTY : VALUE pair model
{
"property1" : val,
"property2" : [],
"property3" : "String",
"property4" : {}
}
The above is a valid JSON cause implies that your property names are wrapped in double quotes " ".
"property" : value
Array (as seen in your Question) cannot be separated by : but with ,
myArr = ["string", {}, value]; // is a valid Array.
with object:
myArr = ["string", {"objectProperty":"val"}, value];
Now to get a key value out of Array:
myArr[0] // "string"
myArr[1] // {object Object}
myArr[1].objectProperty // "val" // get Object property value
So as seen from above Arrays are values stored in numbered keys (0 zero based), while Objects are property - value pairs. What they have in common is the comma (,) delimiter.

Your example isn't a correct JSON object, you should do it like this
var x = { "total": "2" }
x.players = playerArray

Related

How to compare elements in array objects using javascript

I am new to javascript usage.
I have a requirement to compare the field from two different array objects which are having list as below.
Array - A
[
{
"id": "xyz",
"number": "123",
"place": "Here",
"phone": "9090909090"
},
{
"id": "abc",
"number": "456",
"place": "There",
"phone": "9191919191"
},
]
Array - B
[
{
"element1" : "ert",
"id1":"iii",
"element2":"erws",
"element3":"234"
}
,
{
"element1" : "uio",
"id1":"xyz",
"element2":"puy",
"element3":"090"
}
]
The scenario is to compare for each 'id' in the list of array A, with the list of Array B to field 'id1'
Example -
I need to check from Array A -> 'id:xyz' matches the array B object field 'id1'.
Array A - id: xyz should match with id1: xyz in Array B
If the match occurs I need to pull out complete object from the array list A.
here id:xyz matches with id1:xyz
then pull out as below
[
{
"id": "xyz",
"number": "123",
"place": "Here",
"phone": "9090909090"
}
]
Please help me with the suggestions to make this work using javascript.
const A = [
{
"id": "xyz",
"number": "123",
"place": "Here",
"phone": "9090909090"
},
{
"id": "abc",
"number": "456",
"place": "There",
"phone": "9191919191"
},
];
const B = [
{
"element1" : "ert",
"id1":"iii",
"element2":"erws",
"element3":"234"
},
{
"element1" : "uio",
"id1":"xyz",
"element2":"puy",
"element3":"090"
}
];
const C = A.filter(a => B.some(b => b.id1 === a.id));
console.log(C);
// the usage of `const` here means that arrA cannot be re-declared
// this is good for data that should not be changed
const arrA = [{
"id": "xyz",
"number": "123",
"place": "Here",
"phone": "9090909090"
},
{
"id": "abc",
"number": "456",
"place": "There",
"phone": "9191919191"
},
];
const arrB = [{
"element1": "ert",
"id1": "iii",
"element2": "erws",
"element3": "234"
},
{
"element1": "uio",
"id1": "xyz",
"element2": "puy",
"element3": "090"
}
];
// slow method for long lists, fine for short lists or if there are duplicates
// compares each entry in array A to each entry in array B
const out1 = arrA.filter(x => arrB.some(y => x.id === y.id1));
console.log("Example 1: \n", out1);
// faster for long lists
// creates a set of unique values for array B's id1 parameter, ignores duplicates
// then checks that set for each entry in array A
const setB = arrB.reduce((a, b) => {
a.add(b.id1);
return a;
}, new Set());
const out2 = arrA.filter(x => setB.has(x.id));
console.log("Example 2: \n", out2)
.as-console-wrapper { min-height: 100% } /* this is just to make the stack overflow output prettier */

Convert js object array into associative array

By using array.push() I'm updating a following array. I want to add index/key to every object in the object array as I want to check is a record exist with same index/key before pushing new item.
My array is like
$data = [
{
"id": 37,
"permit_id": 1,
"document_description": "zzxc",
"file_name": "zxc"
},
{
"permit_id": "1",
"document_description": "aa",
"file_name": "az"
},
{
"permit_id": "1",
"document_description": "aax",
"file_name": "azx"
}
]
and i want to convert this like
[
0 => {
"id": 37,
"permit_id": 1,
"document_description": "zzxc",
"file_name": "zxc"
},
1 => {
"permit_id": "1",
"document_description": "aa",
"file_name": "az"
},
2 => {
"permit_id": "1",
"document_description": "aax",
"file_name": "azx"
}
]
Is there any way to do this? please give me an idea.
Thank you!
There's no such thing as an associative array in JS. You need to convert it to an object.
You can use spread operator to convert the array to an object: let myObj = {...$data}
let $data=[{id:37,permit_id:1,document_description:"zzxc",file_name:"zxc"},{permit_id:"1",document_description:"aa",file_name:"az"},{permit_id:"1",document_description:"aax",file_name:"azx"}];
let myObj = {...$data}
console.log(myObj);
Update
If you want to search the array to check if an object with a property already exists, you can use Array.some()
let $data=[{id:37,permit_id:1,document_description:"zzxc",file_name:"zxc"},{permit_id:"1",document_description:"aa",file_name:"az"},{permit_id:"1",document_description:"aax",file_name:"azx"}];
let existingObj = {id:37,permit_id:1,document_description:"zzxc",file_name:"zxc"}
let nonexistingObj = {id:38,permit_id:1,document_description:"foo",file_name:"bar"}
if(!$data.some(item => item.id === existingObj.id)){
$data.push(existingObj)
console.log(`ID: ${existingObj.id} pushed`);
}else{
console.log(`ID: ${existingObj.id} already exists!`);
}
if(!$data.some(item => item.id === nonexistingObj.id)){
$data.push(nonexistingObj)
console.log(`ID: ${nonexistingObj.id} pushed`);
}else{
console.log(`ID: ${nonexistingObj.id} already exists!`);
}
console.log($data);
That is basically what you have already. The array of objects is effectively an associative array where the keys are integers - both extend Object.
You can use a forEach loop. Array cannot have key and value pairs like objects so an extra object has to be made so as to keys the values with numbered keys
var x=[
{
"id": 37,
"permit_id": 1,
"document_description": "zzxc",
"file_name": "zxc"
},
{
"permit_id": "1",
"document_description": "aa",
"file_name": "az"
},
{
"permit_id": "1",
"document_description": "aax",
"file_name": "azx"
}
]
var obj={};
x.forEach((e,j)=>{
obj[j+'=>']=e;
})
x=[obj]
console.log(x)

How to make a JSON object out of a dictionary?

I'me new to JavaScript. In the browser I receive a long dictionary like this:
{"cat": "4" , "dog": "5", "fish": "9" }
I'm wondering what is the most efficient way to convert it to a JSON object like:
[
{
"name": "cat",
"value": "4"
},
{
"name": "dog",
"value": "5"
},
{
"name": "fish",
"value": "9"
}
]
You can Loop through it and push each key-value-pair to an Array.
var tValue = {"cat": "4" , "dog": "5", "fish": "9" };
var tList = [];
for(var tKey in tValue) tList.push({name: tKey, value: tValue[tKey]});
console.log(tList);
You can just loop over the dictionary object keys using Object.keys() method, and use .map() method to transform each iterated key/value pair to the appropriate object:
var results = Object.keys(obj).map(function(k) {
return {
name: k,
value: obj[k]
};
});
Demo:
var obj = {
"cat": "4",
"dog": "5",
"fish": "9"
};
var results = Object.keys(obj).map(function(k) {
return {
name: k,
value: obj[k]
};
});
console.log(results);
You can use the function Object.entries to get every key-value pairs and with the function map build the desired output.
let obj = {"cat": "4" , "dog": "5", "fish": "9" },
result = Object.entries(obj).map(([name, value]) => ({name, value}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can do this by this way :
Call a for in loop and read your first object
Push the name and the value in your new object one by one..
Sample code :
var a = {"cat": "4" , "dog": "5", "fish": "9" };
var newJSON = [] ;
console.log(a);
for ( key in a ) {
newJSON.push({name : key, value : a[key]});
}
console.log(newJSON);
You can have this kind of formatted object
{
animals : [
{"name":"cat", "value": 4},
{"name":"dog", "value": 5},
{"name":"fish", "value": 9}
]
}
or like this
[
{"name":"cat", "value": 4},
{"name":"dog", "value": 5},
{"name":"fish", "value": 9}
]

Converting object to array within an object in JavaScript

I am getting back data in a format that is not acceptable to the processing system and I am trying to convert the data. Below is the data I get and the required JSON below that. I tried different things like finding an Object within the data and checking if it has more than one element then converting that object to Array[] but I am unable to do so.
If you have any inputs, I would appreciate it.
if(typeof ob1=== "object" && Object.keys(ob1.length > 1) && typeof Object.keys(ob1) === "object" )
{
console.log(ob1); // I get all the objects and not the parent object i need to change.
}
Present data:
ob1 : {id: 1, details: Object, profession: "Business"}
JSON:
{
"id": "1",
"details": {
"0": {
"name": "Peter",
"address": "Arizona",
"phone": 9900998899
},
"1": {
"name": "Jam",
"address": "Kentucky",
"phone": 56034033343
}
},
"profession": "Business"
}
Required data:
{id: 1, details: Array[2], profession: "Business"}
Required JSON:
{
"id": "1",
"details": [
{
"name": "Peter",
"address": "Arizona",
"phone": 9900998899
},
{
"name": "Jam",
"address": "Kentucky",
"phone": 56034033343
}
],
"profession": "Business"
}
You have to go through the details object and convert it into an array:
var x = {
details: {
0: {a: 1},
1: {a: 2}
}
}
var detailsArr = [];
for(key in x.details) {
detailsArr.push(x.details[key]);
}
x.details = detailsArr;
//x.details = [{a: 1}, {a: 2}]

JSON/Javascript object definition

Trying to identify the type of array, I have an multidimensional JSON array that i pull from a website, but its not using keypairs i am farmiliar with. The structure is as follows. I have only included 1 array item to show what it's doing.
"o": {
"ah": ["id1", "12", "id2", "32", "id4", "4", "id5, "6"]
},
My searches on both JavaScript and JSON objects and strings always use a semi-colon : to define the key and the value.
In the end I just want to loop through the multiple items and print them out.
To provide more clarification about the array structure:
{
"outer": {
"item1":[ {
"c": {
"k": 26862, "n": "theName"
},
"o": {
"ah": ["id1", "0", "id2", "0", "id3", "0.98", "id4", "0.94", "id5", "5", "id6", "-0/0.5"],
"ou": ["id7", "3.5", "id8", "3.5", "id9", "1.53", "id10", "0.55", "id11", "3.4", "id12"],
"1x2": ["id13", "1.20", "id14", "25.00", "id15", "4.80"]
},
"egn":""
}
]
},
{
"item1":[ {
"c": {
"k": 26862, "n": "theName"
},
"o": {
"ah": ["bd1", "0", "bd2", "0", "bd3", "0.98", "bd4", "0.94", "bd5", "0.5", "bd6", "-0.5"],
"ou": ["bd7", "3.5", "bd8", "3.5", "bd9", "1.53", "bd10", "0.55", "bd11", "3.4", "bd12"],
"1x2": ["bd13", "1.20", "bd14", "25.00", "bd15", "4.80"]
},
"egn":""
}
]
}
}
If I wanted to bind an ID to a specific field e.g. and it display the value of ID 1 in the array structure how would I do it without a keypair value, also if the array ID is not standardized so you can't loop through like var = "id"+ i foreach element?
o is an object, ah is an array which is a property of o object. You use JSON.parse() to convert JSON string to javascript object, then iterate over o.ah using Array.prototype.forEach()
// or however you obtain the JSON string
var obj = JSON.parse(jsonStr);
obj.o.ah.forEach(function(value) {
console.log(value);
});

Categories