How to add new key-value pair under Javascript object? - javascript

[{"name":"Top Level","parent":"null"}]
Required output:
[{
"name": "Top Level",
"parent": "null",
"children": [
{
"New_Key":"New_value"
}
]
}]
How can I add "New_Key":"New_value" pair under "parent" key?

var arr = [{"name":"Top Level","parent":"null"}];
for(var i=0; i<arr.length; i++){
arr[i].children = [{
"New_Key":"New_value"
}];
}

its very simple, you can add any new item like obj["key"] = value, in your case you can do it like below
var arrObj = [{"name":"Top Level","parent":"null"}];
for(var i=0; i<arrObj.length; i++){
arrObj[i].children = [{"New_Key":"New_value"}]

Related

How to add new key/value in existing array of SequelizeInstance object in Node/Express Js?

I'm new to Node
I'm trying to add new key/value in array
This is my array and now i'm trying to add value in new data like
const data = [{
"id": 1,
"title": "ABC",
"description": "ABC Details"
}, {
"id": 2,
"title": "PQR",
"description": "PQR Details"
}, {
"id": 3,
"title": "XYZ",
"description": "XYZ Details"
}]
for (let index = 0; index < data.length; index++) {
data[index].info = "New info";
}
console.log(data);
But when i access the "data" array outside for loop cant get added 'info' in data array
It was SequelizeInstance so solution is
for (let index = 0; index < data.length; index++) {
data[index] = data[index].toJSON();
data[index].info = 'my info';
}
console.log(data);
this should work.
How did you try to access 'info'?
console.log(data[0].info) // New info
try :
data.forEach((item) => {
item.info = "New info"
});

How to add a new key to multiple indices of an array of objects?

I've got an array of three people. I want to add a new key to multiple objects at once based on an array of indices. Clearly my attempt at using multiple indices doesn't work but I can't seem to find the correct approach.
var array = [
{
"name": "Tom",
},
{
"name": "Dick",
},
{
"name": "Harry",
}
];
array[0,1].title = "Manager";
array[2].title = "Staff";
console.log(array);
Which returns this:
[
{
"name": "Tom",
},
{
"name": "Dick",
"title": "Manager"
},
{
"name": "Harry",
"title": "Staff"
}
]
But I'd like it to return this.
[
{
"name": "Tom",
"title": "Manager"
},
{
"name": "Dick",
"title": "Manager"
},
{
"name": "Harry",
"title": "Staff"
}
]
You cannot use multiple keys by using any separator in arrays.
Wrong: array[x, y]
Correct: array[x] and array[y]
In your case, it will be array[0].title = array[1].title = "manager";
1st method::
array[0].title = "Manager";
array[1].title = "Manager";
array[2].title = "Staff";
array[0,1] will not work.
2nd method::
for(var i=0;i<array.length;i++) {
var msg = "Manager";
if(i===2) {
msg = "Staff"
}
array[i].title = msg
}
You can use a helper function like this
function setMultiple(array, key, indexes, value)
{
for(i in array.length)
{
if(indexes.indexOf(i)>=0){
array[i][key] = value;
}
}
}
And then
setMultiple(array, "title", [0,1], "Manager");
Try this: `
for (var i=0; var<= array.length; i++){
array[i].title = "manager";
}`
Or you can change it around so var is less than or equal to any n range of keys in the index.
EDIT: instead make var <= 1. The point is to make for loops for the range of indices you want to change the title to.
Assuming that you have a bigger set of array objects.
var array = [
{
"name": "Tom",
},
{
"name": "Dick",
},
{
"name": "Harry",
},
.
.
.
];
Create an object for the new keys you want to add like so:
let newKeys = {
'Manager': [0,2],
'Staff': [1]
}
Now you can add more such titles here with the required indexes.
with that, you can do something like:
function addCustomProperty(array, newKeys, newProp) {
for (let key in newKeys) {
array.forEach((el, index) => {
if (key.indexOf(index) > -1) { // if the array corresponding to
el[newProp] = key // the key has the current array object
} // index, then add the key to the
}) // object.
}
return array
}
let someVar = addCustomProperty(array, newKeys, 'title')

Accessing data in JS structure

I'm trying to parse the following data:
data = [
{"id":"orderBy", "options" : [
{"value":"order-by=newest&", "name":"newest"},
{"value":"order-by=relevance&", "name":"relevance"}
]},
{"id":"searchBy", "options" : [
{"value":"search-by=name&", "name":"name"},
{"value":"search-by=number&", "name":"number"},
{"value":"search-by=date&", "name":"date"},
{"value":"search-by=location&", "name":"location"}
]}
];
Using this data I want to iterate through each object and return its ID, and then all of it options.
I know I need to use for loop like this:
for (var i =0; i < data.length; i++) {
var id = data[i].id;
var optionText = data[i].options[i].text;
var optionValue = data[i].options[i].value;
console.log(id);
console.log(optionText);
console.log(optionValue);
}:
This loop only returns the first OptionText & OptionValue from the data. Can you teach me what I'm doing wrong?
Thanks.
You could use another for loop for the inner array.
var data = [{ "id": "orderBy", "options": [{ "value": "order-by=newest&", "name": "newest" }, { "value": "order-by=relevance&", "name": "relevance" }] }, { "id": "searchBy", "options": [{ "value": "search-by=name&", "name": "name" }, { "value": "search-by=number&", "name": "number" }, { "value": "search-by=date&", "name": "date" }, { "value": "search-by=location&", "name": "location" }] }],
i, j, id, optionText, optionValue;
for (i = 0; i < data.length; i++) {
id = data[i].id;
for (j = 0; j < data[i].options.length; j++) {
optionText = data[i].options[j].name;
optionValue = data[i].options[j].value;
console.log(id, optionText, optionValue);
}
}
data = [
{"id":"orderBy", "options" : [
{"value":"order-by=newest&", "name":"newest"},
{"value":"order-by=relevance&", "name":"relevance"}
]},
{"id":"searchBy", "options" : [
{"value":"search-by=name&", "name":"name"},
{"value":"search-by=number&", "name":"number"},
{"value":"search-by=date&", "name":"date"},
{"value":"search-by=location&", "name":"location"}
]}
];
for (var i in data) {
var id = data[i].id;
console.log(id)
for (var opt of data[i].options){
console.log(opt.value);
console.log(opt.name)
}
}
You lacked an interation loop. Also I believe it could be the perfect example for you to see the difference (and existence?) of iterating through objects and arrays with in and of
You have two levels of arrays you need to loop through. First loop through the outer array, and then through the options of each item:
var data = [{"id":"orderBy","options":[{"value":"order-by=newest&","name":"newest"},{"value":"order-by=relevance&","name":"relevance"}]},{"id":"searchBy","options":[{"value":"search-by=name&","name":"name"},{"value":"search-by=number&","name":"number"},{"value":"search-by=date&","name":"date"},{"value":"search-by=location&","name":"location"}]}];
for (var i = 0; i < data.length; i++) {
var id = data[i].id;
console.log(id);
for(var j = 0; j < data[i].options.length; j++) {
var optionText = data[i].options[j].name;
var optionValue = data[i].options[j].value;
console.log(optionText);
console.log(optionValue);
}
}

JSON data transformation from table-like format to JSON?

I have data that's in this format:
{
"columns": [
{
"values": [
{
"data": [
"Project Name",
"Owner",
"Creation Date",
"Completed Tasks"
]
}
]
}
],
"rows": [
{
"values": [
{
"data": [
"My Project 1",
"Franklin",
"7/1/2015",
"387"
]
}
]
},
{
"values": [
{
"data": [
"My Project 2",
"Beth",
"7/12/2015",
"402"
]
}
]
}
]
}
Is there some super short/easy way I can format it like so:
{
"projects": [
{
"projectName": "My Project 1",
"owner": "Franklin",
"creationDate": "7/1/2015",
"completedTasks": "387"
},
{
"projectName": "My Project 2",
"owner": "Beth",
"creationDate": "7/12/2015",
"completedTasks": "402"
}
]
}
I've already got the column name translation code:
r = s.replace(/\%/g, 'Perc')
.replace(/^[0-9A-Z]/g, function (x) {
return x.toLowerCase();
}).replace(/[\(\)\s]/g, '');
Before I dive into this with a bunch of forEach loops, I was wondering if there was a super quick way to transform this. I'm open to using libraries such as Underscore.
function translate(str) {
return str.replace(/\%/g, 'Perc')
.replace(/^[0-9A-Z]/g, function (x) {
return x.toLowerCase();
})
.replace(/[\(\)\s]/g, '');
}
function newFormat(obj) {
// grab the column names
var colNames = obj.columns[0].values[0].data;
// create a new temporary array
var out = [];
var rows = obj.rows;
// loop over the rows
rows.forEach(function (row) {
var record = row.values[0].data;
// create a new object, loop over the existing array elements
// and add them to the object using the column names as keys
var newRec = {};
for (var i = 0, l = record.length; i < l; i++) {
newRec[translate(colNames[i])] = record[i];
}
// push the new object to the array
out.push(newRec);
});
// return the final object
return { projects: out };
}
DEMO
There is no easy way, and this is really not that complex of an operation, even using for loops. I don't know why you would want to use regex to do this.
I would start with reading out the column values into a numerically indexed array.
So something like:
var sourceData = JSON.parse(yourJSONstring);
var columns = sourceData.columns[0].values[0].data;
Now you have a convenient way to start building your desired object. You can use the columns array created above to provide property key labels in your final object.
var sourceRows = sourceData.rows;
var finalData = {
"projects": []
};
// iterate through rows and write to object
for (i = 0; i < sourceRows.length; i++) {
var sourceRow = sourceRows[i].values.data;
// load data from row in finalData object
for (j = 0; j < sourceRow.length; j++) {
finalData.projects[i][columns[j]] = sourceRow[j];
}
}
That should do the trick for you.

JSON to filtered Array in JavaScript

I have this JSON string:
[
{
"pk": "alpha",
"item": [{
"child": "val"
}]
},
{
"pk": "beta",
"attr": "val",
"attr2": [
"child1"
]
},
{
"pk": "alpha",
"anotherkey": {
"tag": "name"
}
}
]
And I need to produce a filtered array without repeated PK, in the example above the last entry: "pk": "alpha","anotherkey": { ... should be eliminated from the output array. All this using JavaScript. I tried with the object JSON.parse but it returns many key,value pairs that are hard to filter for example "key=2 value=[object Object]".
Any help is greatly appreciated.
var data = JSON.parse(jsonString);
var usedPKs = [];
var newData = [];
for (var i = 0; i < data.length; i++) {
if (usedPKs.indexOf(data[i].pk) == -1) {
usedPKs.push(data[i].pk);
newData.push(data[i]);
}
}
// newData will now contain your desired result
var contents = JSON.parse("your json string");
var cache = {},
results = [],
content, pk;
for(var i = 0, len = contents.length; i < len; i++){
content = contens[i];
pk = content.pk;
if( !cache.hasOwnPropery(pk) ){
results.push(content);
cache[pk] = true;
}
}
// restuls
<script type="text/javascript">
// Your sample data
var dataStore = [
{
"pk": "alpha",
"item": [{
"child": "val"
}]
},
{
"pk": "beta",
"attr": "val",
"attr2": [
"child1"
]
},
{
"pk": "alpha",
"anotherkey": {
"tag": "name"
}
}
];
// Helper to check if an array contains a value
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] == obj) {
return true;
}
}
return false;
}
// temp array, used to store the values for your needle (the value of pk)
var tmp = [];
// array storing the keys of your filtered objects.
var filteredKeys = [];
// traversing you data
for (var i=0; i < dataStore.length; i++) {
var item = dataStore[i];
// if there is an item with the same pk value, don't do anything and continue the loop
if (tmp.contains(item.pk) === true) {
continue;
}
// add items to both arrays
tmp.push(item.pk);
filteredKeys.push(i);
}
// results in keys 0 and 1
console.log(filteredKeys);
</script>

Categories