最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to insert new object in node js array if key not exist - Stack Overflow

programmeradmin1浏览0评论

I want to create data structure like that.

Var ans =[{"b":[1,2]},{"g":[100,2]}]

I want to create a new object within list if key not exists in list ans. Else if key exists in one object of ans list then I want to add new values into the object of ans list

For Example:

Example 1) new data c:{2000}

then

Var ans =[{"b":[1,2]},{"g":[100,2]},{c:[2000]}]

Example 2) new data g:{50}

then

Var ans =[{"b":[1,2]},{"g":[100,2,500]},{c:[2000]}]

I am a beginner in node js, understand array, object concept, but not getting exact logic! Thanks!

I want to create data structure like that.

Var ans =[{"b":[1,2]},{"g":[100,2]}]

I want to create a new object within list if key not exists in list ans. Else if key exists in one object of ans list then I want to add new values into the object of ans list

For Example:

Example 1) new data c:{2000}

then

Var ans =[{"b":[1,2]},{"g":[100,2]},{c:[2000]}]

Example 2) new data g:{50}

then

Var ans =[{"b":[1,2]},{"g":[100,2,500]},{c:[2000]}]

I am a beginner in node js, understand array, object concept, but not getting exact logic! Thanks!

Share Improve this question edited Dec 22, 2018 at 17:10 p u 1,4551 gold badge20 silver badges30 bronze badges asked Mar 7, 2017 at 14:44 Aakash KagAakash Kag 3626 silver badges17 bronze badges 10
  • what is {2000} (in javascript)? – Nina Scholz Commented Mar 7, 2017 at 14:46
  • c:{2000} is not a valid declaration in javascript – Gianpolo Commented Mar 7, 2017 at 14:49
  • 1 You can do var obj = ans.filter(x=>!!x[searchKey])[0]; obj ? obj[searchKey].push(value) : ans.push({searchKey: [value] }) – Rajesh Commented Mar 7, 2017 at 14:54
  • Thanks! @rajesh. Finnaly i got it using your solution – Aakash Kag Commented Mar 7, 2017 at 15:22
  • @Rajesh One problem i noticed in your solution is, when i hold search key in variable then i pass but it is treating variable name as search key.. var xyz="testkey" then if pass xyz in place of search key , so it is search for key 'xyz' instead of 'testkey' – Aakash Kag Commented Mar 7, 2017 at 16:06
 |  Show 5 more ments

3 Answers 3

Reset to default 2

You can try following:

Logic

  • Filter array based on key
  • Check if object with mentioned key exists or not.
  • If yes, push value to this array.
  • If not, create a dummy object and push this object to original array.

Correction, when you do .push({key: value}), key will be considered as string.

Alternates

  1. If you are using ES6, .push({ [key] : value })
  2. Create a dummy object var o = {}. Set key and value to it o[key] = value and push this object.

Optimisations

  • Instead of setting value like obj[key] = value, since we will be operating on arrays, try obj[key] = [].concat(value). This will enable you to pass value as number or array of values.
  • Instead of checking the existence of value in .filter, try Array.isArray to check if value exists and is of type array.

Custom function

function checkAndPush(array, key, value) {
  var filteredList = array.filter(function(o) {
    return Array.isArray(o[key]);
  });

  filteredList.length > 0 ? filteredList[0][key].push(value) : array.push({
    [key]: [].concat(value)
  });
  return array;
}

var ans =[{"b":[1,2]},{"g":[100,2]}]

console.log(checkAndPush(ans, "c", [2,3]))
console.log(checkAndPush(ans, "c", 4));

Prototype function

Array.prototype.checkAndPush = function(key, value) {
  var filteredList = this.filter(function(o) {
    return Array.isArray(o[key]);
  });
  var dummy = {}
  dummy[key] = [].concat(value)

  filteredList.length > 0 ? filteredList[0][key].push(value) : this.push(dummy);
  //  or ES6: this.push({ [key]: [].concat(value) })
  return this;
}

var ans =[{"b":[1,2]},{"g":[100,2]}]

console.log(ans.checkAndPush("c", [2,3]))
console.log(ans.checkAndPush("c", 4));

If you are dealing with objects as your values

ans[key] = ans[key] || []
ans[key].push(value)

Note, this works because your values will be an array. If they could be primatives then you would use hasOwnProperty to check.

if (ans.hasOwnProperty(key)) {
  // Add this to your key somehow
} else {
  // initialize the key with your value
}

Node.js is nothing but a library built on javascript. You can do anything using javascript type of progmming. However push and pop method should be able to help you to deal with nodejs array. ans[key].push(value)

发布评论

评论列表(0)

  1. 暂无评论