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)
Related
I have an array like this:
const data = [{
color:"red",
to:1,
from:2,
opacity:12
}]
I want something like this:
const converted = [{from:2}, {to:1}, {opacity:12}]
What I am trying is:
const mappedData = data.map(({from,to,opacity}) => ({from:from},{to:to},{opacity:opacity}))
but this is not working.
So you can loop through the array and for each object we can get the keys of the objects in the array and use a map to transform them to our desired output, Then the output will return an array, but we can use flatMap which will flatten the arrays returned into a single array of objects!
Thanks pilchard for teaching about flatMap!
const data = [{
color:"red",
to:1,
from:2,
opacity:12
}]
const arr = data.flatMap(x => Object.keys(x).map(data => ({[data]: x[data]})))
console.log(arr);
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]
I have such a object and array which I received response from my server. I need to convert that to second format at below in order to print the value in the website. Is this something need to do object mapping? or parse JSON or please kindly help.
{"header":["SEOUL","BUSAN","NAMPODONG"],"data":[[38,"CAPITAL","M31"]]},
Convert from Above to below
'{"SEOUL" : "38", "BUSAN" : "CAPITAL", "NAMPODONG" : "M31"}'
var finalObj = {};
response.header.forEach(function(item, index) {
finalObj[item] = response.data[0][index];
});
Above code is working fine as it create variable and loop for header and get its value and printed in html. the header and data are from the server so when I enter something let say "A" then it will look for SEOUL header then print 38 in html as tables are looks below.
key value : A
header : SEOUL BUSAN NAMPODONG
data : 38 CAPITAL M31
I do have a lot of data in the database, above is just an example. So let say I enter B then the B is not in database so I want to see the value "No found" in html but this code printing nothing so not sure whether it was proceed or not.
Create a variable & loop over the object.header to get each key and object.data[0] to get its value
var myObj = {
"header": ["SEOUL", "BUSAN", "NAMPODONG"],
"data": [
[38, "CAPITAL", "M31"]
]
}
var tempObj = {};
myObj.header.forEach(function(item, index) {
tempObj[item] = myObj.data[0][index]
})
console.log(tempObj)
As you received it from server – I assume that it is JSON string.
Basically you have two arrays here that you want to reduce to an object.
So I would do it like this:
const object = JSON.parse('{"header":["SEOUL","BUSAN","NAMPODONG"],"data":[[38,"CAPITAL","M31"]]}');
const result = object.header.reduce(function(accumulator, element, i){
accumulator[element] = object.data[0][i] // You had nested array here so I have to get first element.
return accumulator;
}, {});
console.log(result);
I assumed that nested array for data attribute is some kind of formatting mistake. If it's not – you have to map though it's elements first and only then reduce.
You can use zipObj from Ramda library.
The code would look like this:
const res = {"header":["SEOUL","BUSAN","NAMPODONG"],"data":[[38,"CAPITAL","M31"]]}
const obj = R.zipObj(res.header, res.data[0])
console.log(obj)
<script src="//cdn.jsdelivr.net/npm/ramda#latest/dist/ramda.min.js"></script>
You could map the new objects with the wanted keys.
The result is an array with objects, because your data is a nested array with actually only one array. But it looks like taht data could contain more than one row.
var data = { header: ["SEOUL", "BUSAN", "NAMPODONG"], data: [[38, "CAPITAL", "M31"]] },
result = data.data.map(a => Object.assign(...data.header.map((k, i) => ({ [k]: a[i] }))));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can map the data array of arrays into another array of object using as keys the strings in header array:
function transform(obj) {
return obj.data.map(function(subArray) { // for each subArray in the data array
return subArray.reduce(function(o, val, i) { // create a new object o which...
o[ obj.header[i] ] = val; // has key-value pairs where value is the current element of subArray and key is its equivalent (item at the same index) from header array
return o;
}, {});
});
}
var obj = {"header":["SEOUL","BUSAN","NAMPODONG"],"data":[[38,"CAPITAL","M31"], [10,"OTHER","M01"]]};
var result = transform(obj);
console.log(result);
I think the responses above are good as they are, but here is an alternative using reduce in case you didn't know about it
var response = {
"header": ["SEOUL", "BUSAN", "NAMPODONG"],
"data": [
[38, "CAPITAL", "M31"]
]
};
var result = response.header.reduce(function(accum, v, i) {
accum[v] = response.data[0][i];
return accum;
}, {})
console.log(result)
I have a set of JSON data stored in an array. The JSON looks like this:
{
"id": "1",
"key": "2"
}
and I'm trying to sum all of the "key" values inside the array of JSON strings with a for/in loop.
var total = 0;
for (var object in array) {
total += object.value;
}
The expected output is 3. However, this arrangement seems incorrect. I'm working in Node.js. Can anyone point me in the right direction?
If we have an array looking like this:
var array = [{id: "one", key: 2}, {id: "two", key: 8}]
You can simply get the total like that:
var total = array.reduce((x,y) => x + y.key, 0)
However, if you have a JSON string, where the values are also strings (like [{"id":"one","key":"2"},{"id":"two","key":"8"}]'), then you need to parse the JSON first and parse the values as numbers:
JSON.parse(array).reduce((x,y) => x + Number.parseFloat(y.key), 0)
What you have is not an array of objects, but one object with several properties.
You can use Object.keys() to get the properties as an array, then map to retrieve the values for each of those properties, and finally reduce on that array to calculate the sum:
const obj = {
"id": "1",
"key": "2"
}
const total = Object.keys(obj) // Get keys
.map( key => +obj[key] ) // Get values as numbers
.reduce ( (a,b) => a+b ); // sum up
console.log(total);
I am fetching data from a text file and need help in making the information into an object..
Array:
['celestine,timmy,celestinetimmy93#gmail.com,repeat 124\narun,mohan,reach#gmail.com,repeat 124213\njobi,mec,mec#gmail.com,rave\njalal,muhammed,jallu#gmail.com,rave1231212321\nvineeth,mohan,get,rave1231212321\n' ]
I need the values till \n in one object
expected result:
[{'celestine,timmy,celestinetimmy93#gmail.com,repeat 124}
{arun,mohan,reach#gmail.com,repeat 124213}
{jalal,muhammed,jallu#gmail.com,rave1231212321}
{vineeth,mohan,get,rave1231212321} ]
you can do in this way.
after applying splitting by '\n'
['celestine,timmy,celestinetimmy93#gmail.com,repeat
124\narun,mohan,reach#gmail.com,repeat
124213\njobi,mec,mec#gmail.com,rave\njalal,muhammed,jallu#gmail.com,rave1231212321\nvineeth,mohan,get,rave1231212321\n'
]
you will get single one dimensional array.
["celestine,timmy,celestinetimmy93#gmail.com,repeat 124", "arun,mohan,reach#gmail.com,repeat 124213", "jobi,mec,mec#gmail.com,rave", "jalal,muhammed,jallu#gmail.com,rave1231212321", "vineeth,mohan,get,rave1231212321", ""]
Then looping it to get each individual record.
JS :
var test = ['celestine,timmy,celestinetimmy93#gmail.com,repeat 124\narun,mohan,reach#gmail.com,repeat 124213\njobi,mec,mec#gmail.com,rave\njalal,muhammed,jallu#gmail.com,rave1231212321\nvineeth,mohan,get,rave1231212321\n' ]
var arrString = [];
test.forEach(function(val,key){
arrString = val.split('\n')
});
console.log(arrString);
arrString.forEach(function(val,key){
console.log(val.split(','));
})
In order to create an object, you'll need to format the string inside the curly braces as a dictionary of key value pairs. I am not sure what the keys or values are in your case. However if I assume that the key is "key" and the value is the text then:
var txt = 'celestine,timmy,celestinetimmy93#gmail.com,repeat 124\narun,mohan,reach#gmail.com,repeat 124213\njobi,mec,mec#gmail.com,rave\njalal,muhammed,jallu#gmail.com,rave1231212321\nvineeth,mohan,get,rave1231212321\n';
// Use trim, to remove the trailing whitespace, in your case a '\n'
// Use split to convert the text into an array of elements
var arr = txt.trim().split('\n');
// Use the map function to map each string to an object
var objects = arr.map(function(element) {
return { key: element};
});
Here is the output:
objects = [ { key: 'celestine,timmy,celestinetimmy93#gmail.com,repeat 124' },
{ key: 'arun,mohan,reach#gmail.com,repeat 124213' },
{ key: 'jobi,mec,mec#gmail.com,rave' },
{ key: 'jalal,muhammed,jallu#gmail.com,rave1231212321' },
{ key: 'vineeth,mohan,get,rave1231212321' } ]
try this idea.
var x = "celestine,timmy,celestinetimmy93#gmail.com,repeat 124\narun,mohan,reach#gmail.com,repeat 124213\njobi,mec,mec#gmail.com,rave\njalal,muhammed,jallu#gmail.com,rave1231212321\nvineeth,mohan,get,rave1231212321\n";
var y = x.split("\n");
implement the remaining part. convert the array of arrays into array of objects using loops