1

I'm trying to add elements to a JSON from items of an array, but I'm struggling to pass the elements to the JSON.

here is my code:

var j = {
    "Root": {
        "a": "1800,1200,3100",
        "b": "1500,1999,2001",
        "c": "40,60,50",
        "d": "this is not needed",
        "e": "nor this one"
    }
};
var root = j.Root,
    l = root.a.split(",").length,
    hash = ["a", "b", "c"];


for (var i = 0; i < l; i++) {
    for (var x = 0; x < hash.length; x++) {
        root['row_' + i] = {
            "a": root.a.split(",")[i],
            "b": root.b.split(",")[i],
            "c": root.c.split(",")[i] // I don't want to do this for each key
        };
    }
}



for (var x = 0; x < hash.length; x++) {
    delete root[hash[x]];
}

console.log(JSON.stringify(j));

My code is working, but I'm looking for a proper way to use the elements of my array because I will have more than a,b,c

PS: not all key will be used

9
  • There's no such thing as a "JSON Object" What you have is a JavaScript object. Commented Apr 9, 2018 at 10:56
  • Where is the array? What is your expected output? Commented Apr 9, 2018 at 10:56
  • @phuzi, thank you for the remark, can you help ? Commented Apr 9, 2018 at 10:57
  • @AnkitAgarwal the array is the hash, my expected output is correct, but I don't want to explicitly name every element in my loop Commented Apr 9, 2018 at 10:58
  • @Jonathan ok I have added a answer Commented Apr 9, 2018 at 11:00

3 Answers 3

1

You can use Object.keys which will give you the keys for the object in hash variable. Then it will be dynamic for your code to detect all the possible keys in Root object:

var j = {
    "Root": {
        "a": "1800,1200,3100",
        "b": "1500,1999,2001",
        "c": "40,60,50",
        "d": "152,199,21",
        "e": "15,19,200"
    }
};
var root = j.Root,
    l = root.a.split(",").length,
    hash = ["a", "b", "c"];


for (var i = 0; i < l; i++) {
    var obj = {};
    for (var x = 0; x < hash.length; x++) {
        obj[hash[x]] = root[hash[x]].split(",")[i];
    }
    root['row_' + i] = obj;
}


for (var x = 0; x < hash.length; x++) {
    delete root[hash[x]];
}
console.log(root);
console.log(JSON.stringify(j));

Sign up to request clarification or add additional context in comments.

9 Comments

the problem is I will not use all the key of the object, I will only use the ones that can be split
What do you mean by that @Jonathan
@Jonathan check now
@Andreas The keys are not specific. You see that there is a hash variable that says that only the variables in hash needs to be changed for the keys
@Andreas check what the OP asks. He says he only want to have hash variables and not all the keys. So, there might be the case that hash variable is known with the name of the keys.
|
1

You could iterate the keys and build new properties.

var object = { Root: { a: "1800,1200,3100", b: "1500,1999,2001", c: "40,60,50", d: "this is not needed", e: "nor this one" } },
    reference = object.Root;

Object
    .keys(reference)
    .forEach(k => {
        var values = reference[k].split(',');
        if (values.length === 1) {
            return;
        }
        values.forEach((v, i) => {
            reference['row_' + i] = reference['row_' + i] || {};
            reference['row_' + i][k] = v;
        });        
        delete reference[k];
    });

console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

1

You can get your required result using the following methods

  1. reduce()
  2. match()
  3. Object.keys()
  4. Object.values()

DEMO

const root = {
    "Root": {
      "a": "1800,1200,3100",
      "b": "1500,1999,2001",
      "c": "40,60,50",
      "d": "this is not needed",
      "e": "nor this one"
    }
  },
  hash = ["a", "b", "c"],
  keys = Object.keys(root.Root);


let result = Object.values(root.Root).reduce((obj, value, index) => {
  if (value.match(',')) {
    value = value.split(',');
    obj[`row_${index}`] = hash.reduce((object, key, index) => {
      object[key] = value[index];
      return object;
    }, {});
  } else {
    obj[keys[index]] = value;
  }
  return obj;
}, {})

console.log(result);

2 Comments

what happened to d & e ?
@Jonathan I have included d & e as well. Please check

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.