In my script, a function uses the values in my teststim array.
var teststim = ["A", "B", "C"]
And I want to give 'attributes' to these values, so that for example A has the attribute "name", B "birthday", ...
I need to find a way to have access to these attributes. I thought about something like this:
var teststim = {content: "A", attribute: "name"},
{content: "B", attribute: "birthday"},
{content: "C", attribute: "whatever"}
Maybe I'm close than I think, but I am not able to access the 'attribute' values corresponding to the content values. What am I missing?
You need an array of objects:
var teststim = [{content: "A", attribute: "name"},
{content: "B", attribute: "birthday"},
{content: "C", attribute: "whatever"}];
for (var i=0; i<teststim.length; i++) {
var obj = teststim[i];
if (obj.content=='C') {
alert(obj.attribute); // "whatever"
};
};
You can not give properties/attributes to the values of YOUR array.
Therefore, you must start with:
var arr = [
{content:'A'},
{content:'B'},
{content:'C'}
];
Now you can add new attributes, e.g.:
arr[0].attribute = '2';
If you want to map a value in the array to another (longer?) value, you can use:
var mapping = {"A" : "name",
"B" : "birthday",
"C" : "whatever"}
for(var i = 0, len = teststim.length; i < len; i++)
{
alert(mapping[teststim[i]]);
}
If not, then just have an array of objects:
var teststim = [{ 'content' : "A", 'attribute' : "name" },
{ 'content' : "B", 'attribute' : "birthday" },
{ 'content' : "C", 'attribute' : "whatever" }];
for(var i = 0, len = teststim.length; i < len; i++)
{
alert(teststim[i].attribute);
}
Related
I have an array of objects, and and object with arrays as value. I'm trying to take the array from the object and add it as a value to a new key in the objects in the array. When you run the example below you see the object key is instead added as an array of its characters and I'm guessing I'm using Object.values() incorrectly?
So instead of the output being like;
{
"arrkey1": "arrvalue1",
"arrkey2": "arrvalue2",
"newStuff": [
"o",
"b",
"j",
"k",
"e",
"y",
"1"
]
}
How do I instead get what I want like;
{
"arrkey1": "arrvalue1",
"arrkey2": "arrvalue2",
"newStuff": [
"objValue1",
"objValue2",
"objValue3"
]
}
let arr1 = [
{
'arrkey1': 'arrvalue1',
'arrkey2': 'arrvalue2'
},
{
'arrkey3': 'arrvalue3',
'arrkey4': 'arrvalue4'
},
{
'arrkey5': 'arrvalue5',
'arrkey6': 'arrvalue6'
}
];
const obj1 = {
'objkey1': [
'objValue1',
'objValue2',
'objValue3'
],
'objkey2': [
'objValue4',
'objValue5',
'objValue6'
]
};
for (const item in obj1) {
for (let i = 0, x = arr1.length; i < x; i++) {
arr1[i].newStuff = Object.values(item);
}
}
console.log(arr1);
This example inserts a copy of obj1.objkey1 into each element of arr1:
let arr1 = [
{
'arrkey1': 'arrvalue1',
'arrkey2': 'arrvalue2'
},
{
'arrkey3': 'arrvalue3',
'arrkey4': 'arrvalue4'
},
{
'arrkey5': 'arrvalue5',
'arrkey6': 'arrvalue6'
}
];
const obj1 = {
'objkey1': [
'objValue1',
'objValue2',
'objValue3'
],
'objkey2': [
'objValue4',
'objValue5',
'objValue6'
]
};
const combined = arr1.map(item => ({newStuff: [...obj1.objkey1], ...item}));
console.log(combined);
I am learning to use underscore js. I grouped the array. But now i need split array.
I have a grouped JSON array. For example;
var arr = [{"key": "A", "value": ["erdem", "metin", "tamer", "hüseyin"]}]
I want this to be the result.
var arr = [{"key" : "A", "value" : "erdem"},{"key" : "A", "value" : "metin"},{"key" : "A", "value" : "tamer"},{"key" : "A", "value" : "hüseyin"}]
I'm happy if you show me how to do it.
Vanilla JS, without Underscore / lodash :
var arr = [
{"key": "A", "value": ["erdem", "metin", "tamer", "hüseyin"]},
{"key": "B", "value": ["foo", "bar"]}
];
// create modified array of objects
var result = arr.map(item => item.value.map(v => ({ key:item.key, value:v })) );
// print result
console.log( [].concat(...result) );
#forguta you can use this method to get your required output.
var arr = [{"key": "A", "value": ["erdem", "metin", "tamer", "hüseyin"]}]
_.map(arr,function(item){
var temp=[];
_.map(item.value, function(x){
temp.push({key: item.key, value: x});
});
return temp;
});
You can achieve the result without temp variable also (short form)
_.map(arr,function(item){
return _.map(item.value, function(x){
return {key: item.key, value: x};
});
});
How about reduce the main array and then concat each resulting array with a initial empty array
arr.reduce((i, o)=>i.concat(o.value.map(v=>({key: o.key, value: v}))), []);
var arr = [
{"key": "A", "value": ["erdem", "metin", "tamer", "hüseyin"]},
{"key": "B", "value": ["foo", "bar"]}
];
var res = arr.reduce((i, o)=>i.concat(o.value.map(v=>({key: o.key, value: v}))), []);
console.log(res);
I have the following JSON object. I need to remove the duplicates and merge the inner object using plain Javascript. How do I go about doing this?
[{
"id" : 1,
"name" : "abc",
"nodes" :[
{
"nodeId" : 20,
"nodeName" : "test1"
}
]
},
{
"id" : 1,
"name" : "abc",
"nodes" :[
{
"nodeId" : 21,
"nodeName" : "test2"
}
]
}]
Following is the object that I expect as output.
[{
"id" : 1,
"name" : "abc",
"nodes" :[
{
"nodeId" : 20,
"nodeName" : "test1"
},
{
"nodeId" : 21,
"nodeName" : "test2"
},
]
}]
Regards.
Shreerang
First turn the JSON into a Javascript array so that you can easily access it:
var arr = JSON.parse(json);
Then make an array for the result and loop through the items and compare against the items that you put in the result:
var result = [];
for (var i = 0; i < arr.length; i++) {
var found = false;
for (var j = 0; j < result.length; j++) {
if (result[j].id == arr[i].id && result[j].name == arr[i].name) {
found = true;
result[j].nodes = result[j].nodes.concat(arr[i].nodes);
break;
}
}
if (!found) {
result.push(arr[i]);
}
}
Then you can create JSON from the array if that is the end result that you need:
json = JSON.stringify(result);
If your string is called input, then this:
var inter = {};
for (var i in input) {
if (!inter.hasOwnProperty(input[i].name)) {
inter[input[i].name] = input[i].nodes;
inter[input[i].name].name = input[i].name;
inter[input[i].name].id = input[i].id;
}
else
inter[input[i].name] = inter[input[i].name].concat(input[i].nodes)
}
results in:
{"abc":[{"nodeId":20,"nodeName":"test1"},{"nodeId":21,"nodeName":"test2"}]}
You can see how I'm using an intermediate object keyed by whatever the match criterion is. It's an object rather than an array as you asked, but you can iterate it anyway. In fact you're probably better off with this structure than the array you asked for.
BTW, I shoved a couple of text-named properties: "id" and "name" into an array there. They don't show up in JSON.stringify but they're there.
I have this Javascript json array object;
var dataJson=[ [{v:1},{v:90}],[{"v":2},{"v":"33.7000"}] ];
I want to append this array object dataJson to another object such that it looks like this;
var chartObject = {"cols": [
{id: "t", label: "t_label", type: "number"},
{id: "s", label: "s_label", type: "number"}
], "rows": [
{c:
[{v:1},{v:90}] //dataJson[0]
},
{c:
[{"v":2},{"v":"33.7000"}] ////dataJson[1]
}
]};
How do I use a for loop to insert dataJson elements into chartObject? I am sorry I am quite new to javascript and can't even produce some starting code. Thank you very much for any help.
Try this:
...
], "rows": dataJson.map(function(row) {return {c:row};})
};
Javascript objects are pretty amazing things. Just define a new field in chartObject as an array, and then push whatever json data you want into it. It looks you want rows to be an array of objects which have an identifier for each json object, but unless you explicitly want to name each dataJson with a string, then just use an indexed array:
chartObject["rows"] = [];
for(var i = 0; i < dataJson.length; i++) {
chartObject["rows"].push(dataJson[0]);
}
Now you can access each piece of data with:
chartObject["rows"][index]
And each field in the data with:
chartObject["rows"][index]["v"]
Using the simple and clean way:
var chartObject = {"cols": [
{id: "t", label: "t_label", type: "number"},
{id: "s", label: "s_label", type: "number"}
]};
var dataJson=[ [{v:1},{v:90}],[{"v":2},{"v":"33.7000"}] ];
chartObject["rows"] = []; // start with empty array
// iterate over first dataJson array
for(var i = 0, len = dataJson[0].length; i < len; i++){
// push in array `c` mapped to the i-th element of dataJson[0]
chartObject["rows"].push({c : dataJson[0][i]["v"]});
}
console.log(chartObject);
DEMO
Ignore those [object Object] in DEMO
Sample Output:
{
cols: [{
id: "t",
label: "t_label",
type: "number"
}, {
id: "s",
label: "s_label",
type: "number"
}],
rows: [{
c: 1
}, {
c: 90
}]
}
I have a JSON document:
{
Customer: {
Name: "ddd",
Address: [
{Line1: "ABC", zip: [{d:"aa"},{d:"hh"} ,{d:"kk"}]},
{Line1: "XYZ", zip: [{d:"gg"},{d:"ff"}]}
]
}
}
I want the values of
[
"Customer.Address.0.Line1",
"Customer.Address.0.zip.0.d",
"Customer.Address.0.zip.1.d",
"Customer.Address.1.Line1",
"Customer.Address.1.zip.0.d",
"Customer.Address.1.zip.1.d"
]
modified into a new format as below
{
Entity: [
{d:"aa", Line1:ABC},
{d:"hh", Line1:ABC},
{d:"kk", Line1:ABC},
{d:"gg", Line1:XYZ},
{d:"ff", Line1:XYZ}
]
}
I actually need the data as below
{
"Entity.0.d":"aa",
"Entity.0.Line1":"ABC",
"Entity.1.d":"hh",
"Entity.1.Line1":"ABC",
"Entity.2.d":"kk",
"Entity.2.Line1":"ABC",
"Entity.3.d":"gg",
"Entity.3.Line1":"XYZ",
"Entity.4.d":"ff",
"Entity.4.Line1":"XYZ"
}
I need to find the path so that I can reconstruct the JSON.
How do I do that?
You can use dotty
var dotty = require("dotty");
var object = {
a: {
b: {
x: "y",
},
c: {
x: "z",
},
},
};
console.log(dotty.exists(object, "a.b.x")); // true
console.log(dotty.exists(object, ["a", "b", "x"])); // true
console.log(dotty.exists(object, "a.b.z")); // false
console.log(dotty.exists(object, ["a", "b", "z"])); // false
console.log(dotty.get(object, "a.b.x")); // "y"
console.log(dotty.get(object, ["a", "b", "x"])); // "y"
console.log(dotty.get(object, "a.b.z")); // undefined
console.log(dotty.get(object, ["a", "b", "z"])); // undefine
You can do something like:
var newJSON = new Object();
var keyArray = [];
for (var i=0; i< Customer.Address.length; i++){
for (var j=0; j< Customer.Address[i].zip.length; j++){
var innerJSON = new Object();
innerJSON.d = Customer.Address[i].zip[j].d;
innerJSON.Line1 = Customer.Address[i].Line1;
keyArray.push(innerJSON);
}
}
newJSON.key = keyArray;
console.log(JSON.stringify(newJSON)); //This line creates your new JSON string
Of course I am assuming that you have used JSON.parse on your first JSON string :)