I have an associate array with the key is the Id of the item. For example, the item id is 104, therefore the id of the object will be array[104] = {item.info};
So I have this in my component, but every time I am outputting my array it shows 1-103 values and all of them are null. How would I get rid of it and make the array output only what is stored.
JavaScript does not have associative array like in PHP.
What JavaScript has that is most similar to associative array is an object. The difference is that an object is not iterable, while an associative array is iterable.
What you currently do is basically:
const data = []; // [] is an array
data[10] = {
item: 1
};
console.log(data);
What you need to do should be something like this:
const data = {}; // {} is an object
data[10] = {
item: 1
};
console.log(data);
When you do json_encode() in PHP, it is actually converting associative array into a JSON, which is a valid JavaScript object, which do not support associative array as well.
So what it does would be something like this:
$data = [
'10' => [
'item' => 1
]
];
echo json_encode($data);
// output => { "10": { "item": 1 } }
Notice the {} syntax instead of [] syntax.
array doesn't have key, value. it just have value
if you use key, value data form, you should use object
let item = {104: item.info}
how to use object :
item[104]
Related
I'm using Node JS packages and below is the help I want
I have the following JSON data.
[{
"name":"IronMan",
"description":"Genius",
"head_id":"34",
"domain_name":"ironman.com"
}]
I want to access the Value of the keys inside a loop. I don't know how to loop through the above JSON data.
const parsedData= JSON.parse(data) // This will parse your stringifyed Array of objects
parsedData.forEach(entry=> {
// looping through each object in the array and accessing its keys using Object.values()
Object.values(entry).forEach(value=> {
console.log(value) // here you will get all the values of all the objects in an d
})
})
// You can also use
Object.keys(entry).forEach(key => {
// key = 'name'
console.log(entry[key]))
}
// You can also use
Object.entries(entry).forEach(keyValuePair =>{
// keyValuePair = ['name', 'IronMan']
console.log('key', keyValuePair[0])
console.log('value', keyValuePair[1])
})
Learn about the for...in loop then.
let stuff=[{
"name":"IronMan",
"description":"Genius",
"head_id":"34",
"domain_name":"ironman.com"
}];
for(let item of stuff) // this is not the one, just example data is an array
for(let key in item) // this is the one
console.log(key,item[key]);
I am getting a object of multiple array in my angular app from my rest service.
based on property name, I want to access the the value from incoming object.
object is like
data{
array1:{},
array2:{},
array3:{}
}
the number of array can change and also their names. I have another array which has all these array names like...
arraynames = {array1,array2,array3}
I tried to retrieve the value like...
data[arraynames[0]]
or
data[0]
or
data[array1]
but nothing seems working and they are returning undefined.
how can I retrieve the value of array from data.
You can use:
Object.values(data)[0];
//or
data.array1
Your array need to be string array like
arraynames = ['array1','array2','array3']. Now it will work as data[arraynames[0]]
Try:
export class AppComponent {
data = {
array1: {id:1},
array2: {id:2},
array3: {id:3}
}
arraynames =["array1", "array2","array3"]
constructor() {
this.arraynames.forEach(x => {
console.log(this.data[x])
});
}
}
SO I have array1 with values ["folderid":"DTSZ", "folderid":"IEACF6FVGG", "folderid":"IEACKQC6A"] and another array 2 with values ["title":"firsttitle", "title":"second","title":"thirdtitle"]
Now lets say using javascript i want to save it as json object.
[
{"folderid":"DTSZ","title":"firsttitle"},
{"folderid":"IEACF6FVGG", "title":"second"},
{"folderid":"IEACKQC6A", "title":"thirdtitle"}
]
I trying looping and concat but didn't work properly.
array1= ["folderid":"DTSZ", "folderid":"IEACF6FVGG", "folderid":"IEACKQC6A"] ;
array2 = ["title":"firsttitle", "title":"second","title":"thirdtitle"];
Get array with json objects
[
{"folderid":"DTSZ","title":"firsttitle"},
{"folderid":"IEACF6FVGG", "title":"second"},
{"folderid":"IEACKQC6A", "title":"thirdtitle"}
]
In JavaScript an array has just values, in you examples the array is invalid since you try to add direct key: values elements . i.e.
["folderid":"DTSZ"] // invalid !! (notice semicolon)
["folderid", "DTSZ"] // VALID (notice comma)
If you want to translate to a valid array and then to an object, you could use something like entries, which are array of arrays.
Let's take your first example and convert it to entries:
const arr1 = [["folderid", "DTSZ"], ["folderid", "IEACF6FVGG"], ["folderid","IEACKQC6A"]]
Then to convert this to object you can use Object.fromEntries just like this:
const obj1 = Object.fromEntries(entries);
So, focus first to convert your initial invalid arrays to entries, and then the job is done!
use the following code.
var a = [{ "folderid": "DTSZ" }, { "folderid": "IEACF6FVGG" }, { "folderid": "IEACKQC6A" }]
var b = [{ "title": "firsttitle" }, { "title": "second" }, { "title": "thirdtitle" }]
var newObject = a.map((o, index) => {
const temp = Object.assign(o, b[index]);
return temp;
});
console.log('output ---- ', newObject)
I am using DataTables library and I have hard times in receiving data in a proper format so I am trying to adjust it before DataTable library tries to fetch data into table. I have an ajax call which returns an object of the following format:
data:[ [{ Key: "SomeKey" , Value: "SomeValue" } , { ...} ],[...] ]
And my desired output is: data:[ [{ "SomeKey":"SomeValue" } , { ...} ],[...] ]
I have tried JSON.stringify or eval method , but did not worked , also tried those 2 methods when return type was some sort of string but then it inserts \ before " so It does not convert to json. Any help or good tracks would be appreciated.
This has nothing to do with JSON. :-)
data is apparently an array of arrays of objects, where each object has properties valled Key and Value.
If you want to create a new array of arrays of objects, where the objects have a property named by the Key value whose value is the Value value, you can do that like this:
data = data.map(a => a.map(({Key,Value}) => ({[Key]: Value})));
That uses map on the arrays (both the outer and inner ones) and destructuring to pick out the Key and Value properties from each object in the subarrays, and uses computed property names to set the property name on the new object.
In ES5 and earlier, that would look like this:
data = data.map(function(a) {
return a.map(function(obj) {
var newObj = {};
newObj[obj.Key] = obj.Value;
return newObj;
});
});
You should look into Array.prototype.map (mdn)
let data = [[{Key: "SomeKey", Value: "SomeValue"}]];
let output = data.map(a => a.map(({Key, Value}) => ({[Key]: Value})));
console.log(output);
Note the [Key] syntax. To put it simply, whereas var x = 'key'; y = {x: 3} will assign the object {x: 3}, x = 'key'; y = {[x]: 3} will assign the object {key: 3}.
If you're receiving literally the string "data:[ [{ Key: "SomeKey" , Value: "SomeValue" } , { ...} ],[...] ]", then you may trim the first 5 characters ('data:') and then use JSON.parse.
I have data being pulled in from various sources, each returning some form of JSON or similar, although, differently formatted each time. I need to get them all into one array, but I can't figure out how to do it.
The first set is an array like this:
[
Object {id="70", type="ab", dateadded="12345678"},
Object {id="85", type="ab", dateadded="87654321"}, ... more items ...
]
The second set is being pulled in from Facebook, and is like this:
[
Object {id="12341234234", created_time="12345678"},
Object {id="567856785678", created_time="87654321"}, ... more items ...
]
So, I need to alter the second set so that it has 'type', and it has 'dateadded' instead of 'created_time', and then I need to get this all into one array so it can be sorted on 'dateadded'.
How can I do this?
Use the first array's push() method:
// for each item in second array
firstArray.push(convert(item));
function convert(obj) {
// Convert obj into format compatible with first array and return it
}
Hope this helps.
Assuming you have actual valid JSON instead of what you quoted above:
var jsonOld = '[{"id":"70","type":"ab","dateadded":"12345678"},{"id":"85","type":"ab","dateadded":"87654321"}]',
jsonNew = '[{"id":"12341234234","created_time":"12345678"},{"id":"567856785678","created_time":"87654321"}]';
Then first parse these values into actual Javascript arrays:
var mainArr = JSON.parse(jsonOld),
newArr = JSON.parse(jsonNew);
(If you already have actual Javascript arrays instead of JSON strings then skip the above step.)
Then just iterate over newArr and change the properties you need changed:
for (var i = 0, il = newArr.length; i < il; i++) {
newArr[i].type = 'ab';
newArr[i].dateadded = newArr[i].created_time;
delete newArr[i].created_time;
}
And concatenate newArr into mainArr:
mainArr = mainArr.concat(newArr);
And sort on dateadded:
mainArr.sort(function(a, b) { return a.dateadded - b.dateadded; });
This will result in:
[{"id":"70","type":"ab","dateadded":"12345678"},
{"id":"12341234234","type":"ab","dateadded":"12345678"},
{"id":"85","type":"ab","dateadded":"87654321"},
{"id":"567856785678","type":"ab","dateadded":"87654321"}]
See example