i want to change the index of all array elements with other array
this array came from csv file and it may be more than 3 columns
the index array is:
theheadoptions=[
"uid",
"nid",
"name"
];
the main array is:
[
"uid,nid,name",
"1,28807051203034,q",
"2,28807051203035,w",
"3,28807051203036,e",
"4,28807051203037,r",
"5,28807051203038,t",
"6,28807051203039,y",
"7,28807051203040,u",
"8,28807051203041,I",
"9,28807051203042,o",
"10,28807051203043,p",
""
]
i want it become
[
{uid:1,nid:28807051203034,name:q},
{uid:2,nid:28807051203035,name:w},
{uid:3,nid:28807051203036,name:e|,
{uid:4,nid:28807051203037,name:r},
{uid:5,nid:28807051203038,name:t},
{uid:6,nid:28807051203039,name:y},
{uid:7,nid:28807051203040,name:u},
{uid:8,nid:28807051203041,name:I},
{uid:9,nid:28807051203042,name:o},
{uid:10,nid:28807051203043,name:p},
]
i did it
theheadoptions=[
"uid",
"nid",
"name"
];
trs=[
"uid,nid,name",
"1,28807051203034,q",
"2,28807051203035,w",
"3,28807051203036,e",
"4,28807051203037,r",
"5,28807051203038,t",
"6,28807051203039,y",
"7,28807051203040,u",
"8,28807051203041,I",
"9,28807051203042,o",
"10,28807051203043,p",
];
for(i=1;i<trs.length-1;i++){
ndlevel=trs[i].split(splitter);
dddsss(ndlevel,theadoption);
}
function dddsss(arr,heads){
const obj = {};
arr.forEach(function(v,k){
index=k;
obj[heads[k]]=v;
});
console.log(obj);
}
I have a problem with MongoDB.
I have a collection with many documents like this:
{
key1:[
{el:"EL1"},
{el:"EL2"}
]
}
I want to update all documents in the collection col adding a new key key2 where the value is key1.0.
In particular a generic output's document will be:
{
key1:[
{el:"EL1"},
{el:"EL2"}
],
key2: {el:"EL1"}
}
How can I do that?
Thanks
You can use $addFields with $let to generate new field based on key1.0 value and then you can run $out to update existing collection with the result of aggregation:
db.col.aggregate([
{
$addFields: {
"key2.el": {
$let: {
vars: { fst: { $arrayElemAt: [ "$key1", 0 ] } },
in: "$$fst.el"
}
}
}
},
{ $out: "col" }
])
I have an array and object of items, I want to check each item in that array if its path has that object name, I push it in that object array.
So far this is all good, now if no match found I want to create a new item based on that array item name and push it inside it!
All my attempts ending in duplicated value, I think I need a third object/array I just can't think it anymore
To explain better:
cList = {
"rList": {
"Significant": [
{
"Path": "Significant\\Significant Charts",
"Name": "Charts"
}
]
},
};
and
SSList = {
value: [
{
"Name": "Test long name",
"Path": "/someFolder/Test long name",
},
{
"Name": "Untitled",
"Path": "/Significant/Untitled",
}
]
};
My current code
for (var cFolder in this.cList.rList) {
this.SSList.forEach((ssFile)=> {
if(ssFile.Path.indexOf(cFolder) >= 0){
this.cList.rList[cFolder].push(ssFile);
}
});
}
The first item in SSList will not be pushed since it doesn't match, I want to create a array and push it to inside rList
var folderName = ssFile.Path.split("/");
this.cList.rList[folderName[1]].push(ssFile);
One way to do it is to flip your inner and outer loops
let found = false;
this.SSList.value.forEach((ssFile) => {
for (var cFolder in this.cList.rList) {
if(ssFile.Path.indexOf(cFolder) >= 0){
found = true;
break;
}
}
if (found) {
this.cList.rList[cFolder].push(ssFile);
} else {
folderName = ssFile.Path.split("/");
if (!(folderName[1] in this.cList.rList))
this.cList.rList[folderName[1]] = [];
this.cList.rList[folderName[1]].push(ssFile);
}
found = false;
});
I have a js object array like this.
[
{
name:"Japanilainen ravintola Koto",
rating:3.9,
photo:[
{
height:2160,
html_attributions:[
"Hannes Junnila"
],
photo_reference:"CoQBdwAAAMDlivT0nOnYg8jC1txZ3RbfBR59XvKN0WphDbRVUXaUTQclzzaIaXJ8-p7s3x_aG67AUsM_HLNML6pzGl3v_wV2D-eudH_3wy2cB1ROrRgGcGyf4lRuNpE3WwXYbYZu6EK8oEPiJ5B17Lybj-eVbYM2EgVVBgOrUJhsblY1mfxWEhAZ4oHCFakH-hgkbksfGa2uGhQe4aUeOrS2isAir01KUwQ7N3Ce2Q",
width:2269
}
]
},
{
name:"Kin Sushi Helsinki",
rating:4.2,
photo:[
{
height:2988,
html_attributions:[
"Stephan Winter"
],
photo_reference:"CoQBdwAAAN4iMumSbQjtRnJIH1AKRdbSfnI02WGh11r1xaVnZl1ohebKp6zpAS4mmJFqTagrIqUJ39kzulVI0sz2UzzfaVdsAFc5f80PnOCzSLqL5gnpsqv90dVJIqUWD3Bcc9TgYPPs3oGwyekkOsmjQ59o9yqdoF5GzrpaKkojhMNLxpfzEhBKpRkA2CzINpUzAAe3e90TGhQ_KbYCmtJYLfVGIu1kZkzQIAwE4A",
width:5312
}
]
}
]
I get this array above by doing this for each.
response.results.forEach((entry)=>{
var restaurantName = {
"name" : entry.name,
"rating" : entry.rating,
"photo_reference" : entry.photos
}
arr.push(restaurantName);
});
res.send(arr);
And I send the array to my browser so I can see it.
What I am trying to do is to get photo_reference from the entry.photos
I tried entry.photos[0].photo_reference and many more ways and in all of them I am getting a cannot read properly, and now I am not sure how to get that information out.
I edited some of the variable names to make it easier to simulate here, but just map the objects in the photo arrays to their references, and you'll get an array of photo references.
const data = [
{
name:"Japanilainen ravintola Koto",
rating:3.9,
photo:[
{
height:2160,
html_attributions:[
'Hannes Junnila'
],
photo_reference:"CoQBdwAAAMDlivT0nOnYg8jC1txZ3RbfBR59XvKN0WphDbRVUXaUTQclzzaIaXJ8-p7s3x_aG67AUsM_HLNML6pzGl3v_wV2D-eudH_3wy2cB1ROrRgGcGyf4lRuNpE3WwXYbYZu6EK8oEPiJ5B17Lybj-eVbYM2EgVVBgOrUJhsblY1mfxWEhAZ4oHCFakH-hgkbksfGa2uGhQe4aUeOrS2isAir01KUwQ7N3Ce2Q",
width:2269
}
]
},
{
name:"Kin Sushi Helsinki",
rating:4.2,
photo:[
{
height:2988,
html_attributions:[
'Stephan Winter'
],
photo_reference:"CoQBdwAAAN4iMumSbQjtRnJIH1AKRdbSfnI02WGh11r1xaVnZl1ohebKp6zpAS4mmJFqTagrIqUJ39kzulVI0sz2UzzfaVdsAFc5f80PnOCzSLqL5gnpsqv90dVJIqUWD3Bcc9TgYPPs3oGwyekkOsmjQ59o9yqdoF5GzrpaKkojhMNLxpfzEhBKpRkA2CzINpUzAAe3e90TGhQ_KbYCmtJYLfVGIu1kZkzQIAwE4A",
width:5312
}
]
}
]
const arr = []
data.forEach((entry)=>{
var restaurantName = {
"name" : entry.name,
"rating" : entry.rating,
"photo_reference" : entry.photo.map(x => x.photo_reference)
}
arr.push(restaurantName);
});
console.log(arr);
entry.photoes is not defined in your response.results object array.. did you mean to access it as entry.photo (inside your foreach function) ?
I am working on a way to add new JSON data to my existing JSON array:
var resources: JSON = [
"resources": []
]
override func viewDidLoad() {
super.viewDidLoad()
getApiResourceA() { responseObject, error in
var resourceA: JSON = [
"resourceA": []
]
let resourceAResponseObject = JSON(responseObject!)
resourceA["resourceA"] = resourceAResponseObject
self.resources["resources"] = resourceA
}
getApiResourceB() { responseObject, error in
var resourceB: JSON = [
"resourceB": []
]
let resourceBResponseObject = JSON(responseObject!)
resourceB["resourceB"] = resourceBResponseObject
self.resources["resources"] = resourceB
}
}
The structure I am trying to get is:
{
"resources": {
"resourceA": {
"id": 1
"name": "Name1"
}
"resourceB": {
"id": 2
"name": "Name2"
}
}
}
But in my code there are two different "resources"-array created...
Anyone know how to deal with this?
First it is important to understand that JSON is Struct means it is duplicated every time you pass it or use it.
Another issue, you declared resources as Array and not as Dictionary means you can use resource as key.
Declare extensions:
extension JSON{
mutating func appendIfArray(json:JSON){
if var arr = self.array{
arr.append(json)
self = JSON(arr);
}
}
mutating func appendIfDictionary(key:String,json:JSON){
if var dict = self.dictionary{
dict[key] = json;
self = JSON(dict);
}
}
}
use:
//notice the change [String:AnyObject]
var resources: JSON = [
"resources": [String:AnyObject](),
]
resources["resources"].appendIfDictionary("resourceA", json: JSON(["key1":"value1"]))
resources["resources"].appendIfDictionary("resourceB", json: JSON(["key2":"value2"]))
result:
{
"resources" : {
"resourceB" : {
"key2" : "value2"
},
"resourceA" : {
"key1" : "value1"
}
}
}
#daniel-krom has right, but is a little confusing implement the extension, so, we need only add at the end of the Swift controller (or class) that code that adds the "append" methods, nothing else.
Using the appendIfArray method, I could pass from this
[
{
"id_usuario" : 2
}
]
...to this
[
{
"id_usuario" : 2
},
{
"id_usuario" : 111
},
{
"id_usuario" : 112
},
{
"id_usuario" : 113
}
]
The complete code is below:
do{
try json2!["usuarios"][indice]["fotos"][0]["me_gusta"].appendIfArray(json: JSON( ["id_usuario": 111] ))
try json2!["usuarios"][indice]["fotos"][0]["me_gusta"].appendIfArray(json: JSON( ["id_usuario": 112] ))
try json2!["usuarios"][indice]["fotos"][0]["me_gusta"].appendIfArray(json: JSON( ["id_usuario": 113] ))
}catch {
print("Error")
}
The complete JSON structure can find in
http://jsoneditoronline.org/?id=56988c404dcd3c8b3065a583f9a41bba
I hope this can be useful